SQL 查詢時去掉多個count(*)都為0的行
阿新 • • 發佈:2019-02-06
問題:
對於同一個查詢中存在多個count(*),想要將每個count(*)都為0的行去掉。
select a.name ,(select count(*) from b where b.id = a.bid) countB,
(select count(*) from c where c.id = a.cid) countC,
(select count(*) from d where d.id = a.did) countD
from a
結果是:
解決:
在原查詢外面再巢狀一層查詢
select t.* from (
select a.name ,
(select count(*) from b where b.id = a.bid) countB,
(select count(*) from c where c.id = a.cid) countC,
(select count(*) from d where d.id = a.did) countD
from a) t
where (t.countB+t.countC+t.countD)>0
這樣的結果就可以把三者都為0的行去掉了