Reputation: 43872
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?
Upvotes: 2
Views: 766
Reputation: 49089
You need to use a LEFT JOIN
, that returns all rows from Posts
, and rows from Comments
only when the JOIN succeedes. If the join doesn't succeed because there are no comments with comments.postid=posts.id
, you still get all values from Posts
, but values from Comments
will 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 return Posts.date
instead.
And the final query is this:
SELECT Posts.id
FROM Posts LEFT JOIN Comments
ON Posts.id = Comments.postid
GROUP BY Posts.id
ORDER BY coalesce(max(Comments.date),Posts.date) ASC
Upvotes: 3
Reputation: 1270713
You need a left outer join to take into account that there may be no comments:
SELECT Posts.id
FROM Posts left JOIN
Comments
ON Posts.id = Comments.postid
group by posts.id
ORDER BY coalesce(max(Comments.date), posts.date) ASC
Upvotes: 1