我有两张桌子:
表1。 options_ethnicity
,其中包含以下条目:
ethnicity_id ethnicity_name
1 White
2 Hispanic
3 African/American
表2。 inquiries
包含以下条目:
inquiry_id ethnicity_id
1 1
2 1
3 1
4 2
5 2
我想生成一个表格,显示按种族划分的查询次数。到目前为止,我的查询看起来像这样:
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
如果我用右连接替换LEFT 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
答案 0 :(得分:5)
因为您正在使用LEFT JOIN,所以对LEFT JOIN中定义的表的引用可以为null。这意味着您需要将此NULL值转换为零(在本例中):
SELECT oe.ethnicity_name,
COALESCE(COUNT(i.ethnicity_id), 0) AS count
FROM OPTIONS_ETHNICITY oe
LEFT JOIN INQUIRIES i ON i.ethnicity_id = oe.ethnicity_id
GROUP BY oe.ethnicity_id
此示例使用COALESCE,一种处理NULL值的ANSI标准方法。它将返回第一个非null值,但如果找不到任何值,则返回null。 IFNULL是MySQL的有效替代品,但在COALESCE的情况下它不能移植到其他数据库。
在真实数据库表中,在查询表中有一些条目,其中ethnicity_id为NULL,即未记录种族。有关如何计算这些空值以便显示它们的任何想法吗?
我想我理解你所面临的问题:
SELECT oe.ethnicity_name,
COALESCE(COUNT(i.ethnicity_id), 0) AS count
FROM (SELECT t.ethnicity_name,
t.ethnicity_id
FROM OPTIONS_ETHNICITY t
UNION ALL
SELECT 'NULL placeholder' AS ethnicity_name,
NULL AS ethnicity_id) oe
LEFT JOIN INQUIRIES i ON i.ethnicity_id = oe.ethnicity_id
GROUP BY oe.ethnicity_id
这将获取所有NULL ethncity_id实例,但它会将计数归属于“NULL占位符”组。 IE:
ethnicity_name | COUNT
------------------------
White | 3
Hispanic | 2
NULL placeholder | ?
答案 1 :(得分:3)
您计算了一个字符串而不是右列
SELECT options_ethnicity.ethnicity_name, COUNT(inquiries.ethnicity_id) AS count
FROM inquiries
RIGHT JOIN options_ethnicity ON options_ethnicity.ethnicity_id = inquiries.ethnicity_id
GROUP BY options_ethnicity.ethnicity_id
答案 2 :(得分:1)
为什么不“反向”查询?
SELECT
options_ethnicity.ethnicity_name,
COUNT(inquiries.ethnicity_id) AS count
FROM
options_ethnicity
Left Join inquiries On options_ethnicity.ethnicity_id = inquiries.ethnicity_id
GROUP BY
options_ethnicity.ethnicity_id
你仍然可能需要Coalesce调用,但对我来说,这个查询对你想要完成的事情更有意义。