I’m building a discussion board… I have a table containing the posts and another containing comments… foreign id is the post_id. Now, I’m trying to sort the posts based on number of comments each has. Query I’m currently using:
SELECT username, posts.post_id, category_id, UNIX_TIMESTAMP(posts.datetime) AS datetime, posts.body, posts.owner_id, COUNT(comment_id) AS number
FROM posts, comments, user
WHERE posts.post_id = comments.post_id AND posts.owner_id = user.`id`
GROUP BY comments.post_id
ORDER BY number DESC
The query works fine, but the problem is that posts that don’t have comments are not selected. I want to display posts not minding if they have comments or not but I want to sort them by number of comments.
Use LEFT Join. Your From/where joint is equivalent to INNER JOIN :