我有以下语句,它工作正常,除了如果第二个表没有对第一个表的引用项,它将不返回任何结果。
我需要的是将 count(p.match_id) AS matchcount
返回为 0
"SELECT c.*, count(p.match_id) AS matchcount
FROM ci_address_book c LEFT JOIN ci_matched_sanctions p
ON c.id = p.addressbook_id
GROUP BY p.addressbook_id ORDER BY c.id LIMIT ".$offset.",".$num;
最佳答案
这里的第一个问题是您正在使用 LEFT JOIN
。这意味着 c
中的所有行都将被返回,即使它们与 p
中的行不匹配也是如此。
你的问题。
if the 2nd table has no reference items to the first table it will return no results
让我用自己的话重新表述一下。
if the p table has no reference items to the c table it will not return any results
当您执行 LEFT JOIN 时,“右”表中的任何空表都将返回 NULL 值。因此在这些情况下 matchcount 将为“NULL”。 (您可以通过执行 select c.*, p.* ... where p.addressbook_id = NULL
来测试)
要改为显示“0”,请执行以下操作:
SELECT c.*, COALESCE(COUNT(p.match_id), 0) AS 匹配计数
COALESCE
返回第一个非 NULL 值。所以当 COUNT(p.match_id) 为 NULL 时,你得到 0。
关于sql查询返回0而不是NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201235/