减去两个表之间的计数

时间:2016-08-13 19:22:06

标签: mysql sql

我正在使用MySQL

如何从另一个表中减去记录来计算。 例如,count = 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         +
+-------------+----------------+

1 个答案:

答案 0 :(得分: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
                 );