Skip to content
Advertisement

SQL merge two tables – get only one row for each key value

I’m trying to run an SQL command on my database. I have two tables, one for users, another one for posts. I want to find last post of each user. I tried following:

It fails with error “your syntax is weird near GROUP BY b.username on line 5″. I tried to run the command with while loop (on the webpage) like this:

But it looks like the second query is completely ignored, I get default values even though manually typing the query into database gets 2 or 3. I know that running like 50 queries in a loop probably isn’t a good idea, that’s why I’m trying to do it all at once. This code:

results in

The order is correct, I want just the upper row for each user. I’d appreciate any help.

Advertisement

Answer

You actually need to filter, not group. You can do this with a correlated subquery:

In MySQL 8.0, you can use window functions:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement