1

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.

2
  • What is the need of "post_id" in the table POST_CATEGORIES ? does this mean that for EACH POST you will have NEW category_id ? It doesn't make sense. CATEGORY TO POSTS should be 1:n . You have 1:1 which is probably not the best way for a blogging application. Commented Nov 8, 2010 at 15:24
  • Not sure how to make your query work exactly for you but I can offer some other info. I know you dont want to create a row for the uncategorized but why? Is it bcause you dont want that to appear on other areas of your site? If thats the case then alter your SQl to not return results that have category_id of 0. If its an absolute no to have a row with uncategorized then you could do two queries one that returns your posts and one that returns your categories table then use PHP to do the math and if one of the posts has a category id of 0 then give it the category of uncategorized. Commented Nov 8, 2010 at 15:28

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Great, thank you. If they don't have a category_name, how would I call them from the results?
The fields category_id, category_name and post_id from post_categories will all be NULL for posts without a category, so in PHP you can simply check if $row['category_name'] === NULL.
Thanks for your help with this so far. I've just given the SQL a test and it doesn't seem to return anything as null, even when executed in PhpMyAdmin?
Seems to work with RIGHT JOIN, not LEFT JOIN. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.