简体   繁体   English

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

[英]SQL - Display all empty rows with Count() Group By

These are my tables: 这些是我的表:

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


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

One category has many Items 一个类别有很多项目

One item have one category 一个项目有一个类别

Let's say I have these data: 假设我有这些数据:

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

Query that I used to count items grouped by category name: 用于计算按类别名称分组的项目的查询:

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

I've tried the above query to display the counting, but it doesn't show all rows from Categories table. 我已经尝试了上面的查询来显示计数,但它没有显示Categories表中的所有行。 Well, of course some item might not be in a category, but how do I show the empty Category as well? 好吧,当然有些项目可能不属于某个类别,但我如何显示空类别呢?

could you try this? 你能试试吗?

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

to print out ONLY empty categories 打印出只有空类别

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM