获取剩余的行

时间:2012-02-24 17:14:02

标签: mysql sql

请参阅下面的SQL查询,它会计算与numbersbusiness表匹配的总记录数。

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?

2 个答案:

答案 0 :(得分:2)

您是说有businessnumbers行在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