Skip to content
Advertisement

MySQL Group By for sorted table

I’ve two tables with these structures:

Table 1 (comments)

Table 2 (posts)

My goal is to get a list with the latest comment from each post of a specific category_id.

So for example, if I have category 1 as input I need the comments with the id 2 and 1 because these are always the last comments for each post with the given category.

Until now, I got this query which returns all entries ordered by the creation date.

I’ve read about the group by property but this does not guarantee me to get the last entries. How can I solve this problem?

Advertisement

Answer

Assuming that Table2 is the categories table, if you want in the results only the columns of Table1 then you don’t need a join.
Use NOT EXISTS:

or with a correlated subquery:

Edit:

See the demo.
Or:

See the demo.
Replace ? with the category_id you want to search for.
Results:

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