问题
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