SQL - 使用Count()Group By显示所有空行

时间:2013-12-05 07:08:59

标签: mysql sql database

这些是我的表格:

Categories table
================
id (fk)
category_name


Items table
===========
id (pk)
item_name
category_id (pk)

一个类别有多个

一个有一个类别

假设我有这些数据:

Categories
==========
id       category_name
-----------------------
1        Foods
2        Beverages
3        Computer
4        Cats


Items
=====
id    item_name   category_id(fk)
1     Rice        1
2     Chicken     1
3     Mouse       3
4     Keyboard    3

查询我以前按类别名称分组的项目:

SELECT
    categories.id,
    categories.category_name,
    COUNT(items.item_name) AS items
FROM
    items
INNER JOIN categories ON items.category_id = categories.id
GROUP BY
    category_name

我已经尝试过上面的查询来显示计数,但它没有显示Categories表中的所有行。好吧,当然有些项目可能不在一个类别中,但我如何显示空类别?

1 个答案:

答案 0 :(得分:3)

你能试试吗?

SELECT
    categories.id,
    categories.category_name,
    COUNT(items.item_name) AS items
FROM
    categories LEFT JOIN items
        ON items.category_id = categories.id
GROUP BY
    categories.id, category_name

打印出仅空类别

SELECT
    categories.id,
    categories.category_name
FROM
    categories LEFT JOIN items
        ON items.category_id = categories.id
WHERE items.category_id IS NULL;