SQL Query也可以获得空类别 [英] SQL Query to get empty categories too
本文介绍了SQL Query也可以获得空类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的类别
表中,我有: cat_id
, cat_name
, cat_slug
。
在表格项目
中,我有: item_title,
item_id
, item_category
。
`item_category` =`cat_id`
我使用以下SQL来获取所有类别以及它们有多少项:
SELECT *,COUNT(`item_id`)
FROM`menu_categories`
JOIN`menu_items` ON` item_category` =`cat_id`
GROUP BY`item_category`
但它没有显示空类别
,即类别
不包含项目。
解决方案
您需要使用 LEFT JOIN
而不是 JOIN
SELECT *,COUNT(`item_id`)
FROM`menu_categories`
LEFT JOIN`menu_items` ON`item_category` = cat_id`
GROUP BY`item_category`
查看 SQL连接的可视化解释。
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.
解决方案
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.
这篇关于SQL Query也可以获得空类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文