I have a table, called Posts, and a second table, called Comments. These are linked by an id column in the posts table, and a postid column in the comments table.
Both tables have a date column, which is the date when they were posted. I want to be able to sort my posts based on the newest activity, so they should be sorted by the post’s date (if there are no comments) or the newest comment’s date.
In order to do this, I’ve constructed this simple query:
SELECT Posts.id FROM Posts
INNER JOIN Comments ON Posts.id = Comments.postid
ORDER BY Comments.date ASC
Unfortunately, this has a very obvious problem. If there are no comments on a post, it will be ignored. If there are multiple comments on a post, it will show up multiple times in the results.
How can I construct a query to satisfy these requirements?
You need to use a
LEFT JOIN, that returns all rows fromPosts, and rows fromCommentsonly when the JOIN succeedes. If the join doesn’t succeed because there are no comments withcomments.postid=posts.id, you still get all values fromPosts, but values fromCommentswill be Null.You then have to use
GROUP BY, so you will get only one row for each ID, and you can use MAX() aggregate function to get the maximum date in comments table.If there are no comments,
max(comments.date)will be Null, so COALESCE will returnPosts.dateinstead.And the final query is this: