我有两个表:
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
在上面的例子中,我只想得到来自TableA
的num_of_recods
与来自TableB
的count(*)
不匹配的记录,因此基于上面的结果将是:
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
的情况。