2016-08-13 72 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 
       );