php mysql:计算另一个表

时间:2018-05-18 07:19:54

标签: php mysql mysqli

我现在有这种表

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中存在并根据块名对其进行排序,是否可能?因为我需要计数结果显示为图表

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以使用以下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;

如果有效,请告诉我。 感谢。