我有2个表:MySQL的COUNT与非零项
表1.options_ethnicity
带有以下各项:
ethnicity_id ethnicity_name
1 White
2 Hispanic
3 African/American
表2inquiries
带有以下各项:
inquiry_id ethnicity_id
1 1
2 1
3 1
4 2
5 2
我想生成一个表,其中显示inqu数量由族裔ireless。我的查询到目前为止是这样的:
SELECT options_ethnicity.ethnicity_name, COUNT('inquiries.ethnicity_id') AS count
FROM (inquiries
LEFT JOIN options_ethnicity ON
options_ethnicity.ethnicity_id = inquiries.ethnicity_id)
GROUP BY options_ethnicity.ethnicity_id
查询给出了正确的答案,但有非洲/美国具有0的结果没有列。
White 3
Hispanic 2
如果我更换留下了右连接JOIN,我得到的所有3个种族名称,但对于非洲/美国计数是错误的。
White 3
Hispanic 2
African/American 1
任何帮助,将不胜感激。
这里有一个更新这则讯息似乎是一个工作查询:
SELECT
options_ethnicity.ethnicity_name,
COALESCE(COUNT(inquiries.ethnicity_id), 0) AS count
FROM options_ethnicity LEFT JOIN inquiries ON inquiries.ethnicity_id = options_ethnicity.ethnicity_id
GROUP BY options_ethnicity.ethnicity_id
UNION ALL
SELECT
'NULL Placeholder' AS ethnicity_name,
COUNT(inquiries.inquiry_id) AS count
FROM inquiries
WHERE inquiries.ethnicity_id IS NULL
工作查询 - 将UNION更改为'UNION ALL' - 不删除重复项。 – 2010-07-13 00:18:54
是的,你是对的。我已经将UNION更改为UNION ALL,这应该会更快。 – Mitchell 2010-07-13 13:11:23