I am designing a custom blog in PHP. On my panel I have the heading "Categories" and I list the categories and how many posts are in each category. There are 2 related tables, posts, and post_categories.
POSTS - post_id, post_title, post, category_id
POST_CATEGORIES - category_id, category_name, post_id
I'd prefer not to add a category of uncategorised as this will cause me issues with future features I plan to design. My SQL for this is:
SELECT *, COUNT(*) AS category_post_count
FROM post_categories, posts
WHERE posts.category_id = post_categories.category_id
GROUP BY category_name
Now if a post is not set with a category_id, it is given a category_id of 0 and will not related to anything in post_categories. How can 开发者_开发问答I group these in my SQL statement AS uncastegorised?
Thanks.
You can do a left join to also include any posts that don't have a category.
SELECT *, COUNT(*) as category_post_count
FROM post_categories LEFT JOIN posts
ON posts.category_id = post_categories.category_id
GROUP BY category_name;
精彩评论