我有以下MYSQL查询:
SELECT categories.key, categories.name, count(*) as itemsCount
FROM categories
LEFT JOIN designs
ON categories.key = designs.category
GROUP BY categories.name ASC
它负责选择所有类别并计算属于每个类别的设计数量。但是,我的应用程序和数据库设置为如果“category
”表中的“designs
”字段的值为“0”,则此设计属于虚拟(没有) “key = 0
”表格中的categories
类别“unassigned
”类别。
我的问题是...... 是否可以修改我的查询以计算不属于任何现有类别的设计?
也许我过于复杂化了,添加一个带有“0”键的类别要容易得多,但为了学习,也许有更好的方法?
感谢。
答案 0 :(得分:2)
这只是达到你想要的东西的快捷方式,我相信有更聪明的东西。
SELECT categories.key, categories.name, count(designs.category) as itemsCount
FROM categories
LEFT JOIN designs
ON categories.key = designs.category
GROUP BY categories.key ASC
UNION ALL
SELECT 0,'VIRTUAL',COUNT(*) AS itemsCount
FROM designs
WHERE category = 0
答案 1 :(得分:2)
SELECT d.category, c.name, COUNT(d.category)
FROM (
SELECT 0 AS key, 'VIRTUAL' AS name
UNION ALL
SELECT key, name
FROM categories
) c
LEFT JOIN
designs d
ON d.category = c.key
GROUP BY
c.key