2016-08-13 73 views
-1

我正在使用MySQL减去两个表之间的计数

我如何计算从另一个表中减去记录。 例如,数= TAB1 - TAB2

表:TAB1

+-------------+----------------+ 
| studnetId + batchId  + 
+-------------+----------------+ 
+ 1  +  1   + 
+-------------+----------------+ 
+ 2  +  1   + 
+-------------+----------------+ 
+ 3  +  1   + 
+-------------+----------------+ 
+ 4  +  1   + 
+-------------+----------------+ 
+ 5  +  2   + 
+-------------+----------------+ 
+ 6  +  2   + 
+-------------+----------------+ 
+ 7  +  2   + 
+-------------+----------------+ 

表:TAB2

+-------------+----------------+ 
| studnetId + batchId  + 
+-------------+----------------+ 
+ 1  +  1   + 
+-------------+----------------+ 

预期结果

+-------------+----------------+ 
| count  + batchId  + 
+-------------+----------------+ 
+ 3  +  1   + 
+-------------+----------------+ 
+ 2  +  2   + 
+-------------+----------------+ 
+0

我在计算学生ID – fresher

+0

当'batchId'是'2'时,count不应该是'3'吗? – sgeddes

回答

0

下面是使用outer join另一种方法:

select t1.batchId, count(t1.studnetId) - count(t2.studnetId) as cnt 
from t1 
     left join t2 on t1.batchId = t2.batchId and t1.studnetId = t2.studnetId 
group by t1.batchId 

而且我相信当batchId = 2,在count3,不2如您预期的结果。

0

如果我理解正确的,你可以使用not exists

select count(*), batchid 
from tab1 t1 
where not exists (select 1 
        from tab2 t2 
        where t2.studnetid = t1.studnetid and t2.batchid = t1.batchid 
       );