Okay so I have two tables, a category table and a posts table.
I was hoping to construct a query that would return each category, the last record in the post table for that category (category.id = post.category_id) AND the rowcount of all posts with post.category_id = category.id)
i.e
A list of categories, each with the record of the latest post for the category and the number of posts in that category.
I’ve tried various joins and subselects, and I have managed to get a list of categories, their post count, and their FIRST post (I need the last).
I have also managed to get a list of categories and their LAST post, but not the post count.
Any help/directions will be much appreciated!
Try this:
This assumes that you have a column
post_idthat is strictly increasing and unique.If you have no such field but you have for example
post_datethat is not unique, you may get two rows for some categories in rare cases where two posts have exactly the same timestamp.To also get categories without posts use a LEFT JOIN:
If you need more columns from each table you can join the result above with the original tables: