如何比较多行中两个不同列的计数,并仅查找不匹配项



我有两个表:

Table A
--------- 
id | num_of_records
---|---------------
10 | 2
20 | 9
30 | 1
40 | 3
Table B
---------
id | details
---| --------
10 | somedetail 2
10 | somedetail 3
20 | foobar
30 | random
40 | random 2

在上面的例子中,我只想得到来自TableAnum_of_recods与来自TableBcount(*)不匹配的记录,因此基于上面的结果将是:

id | difference
---| --------
20 | 8
40 | 2

我真正的TableB有大约20M条记录,TableA有大约4k条记录。

我写了这样的东西,但select id from tableA join on tableB where tableA.num_of_records <> (select count(*) from tableB where id = id);不起作用

您可以使用full join:

select id, coalesce(a.num_of_records, 0) - coalesce(b.cnt, 0)
from a full join
(select id, count(*) as cnt
from b
group by id
) b
using (id)
where a.num_of_records is distinct from b.cnt;

这使用full join来处理其中一个表缺少id的情况。

最新更新