请参阅下面的SQL查询,它会计算与numbers
和business
表匹配的总记录数。
SELECT N.mobile, B.name, count(*) as Total FROM records as R
LEFT JOIN business as B ON B.id = R.business_id
LEFT JOIN numbers as N ON N.id = R.numbers_id
group by N.mobile, B.name
但是,剩余的行(N.mobile, B.name
)未包含在结果中,如何包含它们而Total
将为0?
答案 0 :(得分:2)
您是说有business
和numbers
行在records
中没有条目,但您想将它们包含在计数中?由于MySQL不支持FULL OUTER JOIN
使用UNION
来获得您想要的结果:
SELECT N.mobile, B.name, count(*) as Total FROM records as R
LEFT JOIN business as B ON B.id = R.business_id
LEFT JOIN numbers as N ON N.id = R.numbers_id
GROUP BY N.mobile, B.name
UNION
SELECT N.mobile, NULL, 0
FROM numbers AS N
LEFT JOIN records as R ON N.id = R.numbers_id
WHERE r.numbers_id IS NULL
UNION
SELECT NULL, B.Name, 0
FROM business AS B
LEFT JOIN records as R ON B.id = R.business_id
WHERE r.business_id IS NULL
答案 1 :(得分:0)
用户OUTER JOIN而不是INNER JOIN以包含这些丢失的记录:
SELECT N.mobile, B.name, count(*) as Total
FROM records as R
OUTER JOIN business as B ON B.id = R.business_id
OUTER JOIN numbers as N ON N.id = R.numbers_id
group by N.mobile, B.name