SQL Query to get empty categories too

那年仲夏 提交于 2019-12-25 07:24:11

问题


In my categories table I have: cat_id, cat_name, cat_slug. In the table items I have: item_title, item_id, item_category.

`item_category` = `cat_id`

I'm using the following SQL to get "all" categories and how many items they have:

SELECT *, COUNT(`item_id`) 
FROM `menu_categories` 
    JOIN `menu_items` ON `item_category` = `cat_id` 
GROUP BY `item_category`

But it doesn't show empty categories, i.e. categories without items.


回答1:


You need to use LEFT JOIN instead of JOIN

SELECT *, COUNT(`item_id`) 
FROM `menu_categories`
  LEFT JOIN `menu_items` ON `item_category` = `cat_id`
GROUP BY `item_category`

Have a look at A Visual Explanation of SQL Joins.




回答2:


Use a LEFT JOIN

SELECT *, COUNT(`item_id`) 
FROM `menu_categories` 
    LEFT JOIN `menu_items` 
        ON `item_category` = `cat_id` 
GROUP BY `item_category` 


来源:https://stackoverflow.com/questions/12177444/sql-query-to-get-empty-categories-too

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!