使用左连接加入2个查询

时间:2015-06-25 00:29:22

标签: mysql sql

这些是我的查询,我打算将它们加入并创建一个,但不确定如何。

select SN, COUNT(distinct SB)
from SBS
where SB is not null
group by SN  
order by COUNT(Distinct SB) desc


select a.SN, COUNT(distinct a.SB)
from SBS a 
inner join SC b
on a.CN = b.CN
group by a.SN
order by COUNT(distinct a.SB) desc

2 个答案:

答案 0 :(得分:0)

也许你可以使用像

这样的联盟
select SN, COUNT(distinct SB)
from SBS
where SB is not null
group by SN  
order by COUNT(Distinct SB) desc

union

select a.SN, COUNT(distinct a.SB)
from SBS a 
inner join SC b
on a.CN = b.CN
group by a.SN
order by COUNT(distinct a.SB) desc

答案 1 :(得分:0)

一种方法是创建一个包含两列的查询,每列一个。

为此,您可以使用left join然后聚合:

select a.SN,
       COUNT(distinct case when a.sb is not null then a.SB end) as firstQueryCount,
       COUNT(distinct case when b.CNT is not null then a.SB end) as secondQueryCount
from SBS a left join
     SC b
     on a.CN = b.CN
group by a.SN
order by firstQueryCount desc;