由于您使用的是LEFT JOIN,因此对LEFT JOIN中定义的表的引用可以为空。这意味着您需要将此NULL值转换为零(在这种情况下):
SELECt oe.ethnicity_name,COALESCE(COUNT(i.ethnicity_id), 0) AS count FROM OPTIONS_ETHNICITY oeLEFT 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 tUNIOn ALLSELECT 'NULL placeholder' AS ethnicity_name, NULL AS ethnicity_id) oeLEFT 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 | 2NULL placeholder | ?



