mysql:计算其他表中不存在的元素数

n53p2ov0  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(369)

我现在有这种table

table a
==============
pid |   block
--------------
1   |   1
2   |   1
3   |   2
4   |   3
5   |   2
6   |   3
--------------

table b
==============
cid |   pid
--------------
1   |   1
2   |   3
3   |   5
--------------

output (count each block who no exist on table b)
===================
block   |   total
-------------------
1       |   1 <--- because on table b exist 1 from 2
2       |   0 <--- because on table b exist 2 from 2
3       |   2 <--- because on table b not exist
-------------------

所以基本上我需要计算有多少块不在表b中,但在表a中,并根据块名对其排序,这可能吗?因为我需要将计数结果显示为图表

ebdffaop

ebdffaop1#

select a.block
, 2 - count(distinct b.cid) 
from a
left join b on a.pid = b.pid
group by 1
jhdbpxl9

jhdbpxl92#

可以使用以下sql:

select outera.block , count(outera.block)- (select count(b.pid) from a left join b on a.pid=b.pid  where a.block=outera.block
 group by a.block) as acount  
from a as outera group by outera.block;

请让我知道它是否有效。谢谢。

相关问题