首页 > 解决方案 > 子查询与多表连接

问题描述

我有 3 个表 A、B、C。我想列出交叉点数。

方式1:-

select count(id) from A a join B b on a.id = b.id join C c on  B.id = C.id;

结果计数 - X

方式2:-

SELECT count(id) FROM A WHERE id IN (SELECT id FROM B WHERE id IN (SELECT id FROM C));

结果计数 - Y

每个查询中的结果计数不同。究竟是什么问题?

标签: sqlinner-joinnested-queries

解决方案


AJOIN可以乘以行数以及过滤掉行。

在这种情况下,第二个计数应该是正确的,因为没有重复计算 - 假设ida. 如果没有,则需要count(distinct a.id).

等效的 usingJOIN将使用COUNT(DISTINCT)

select count(distinct a.id)
from A a join
     B b
     on a.id = b.id join
     C c
     on B.id = C.id;

我提到这一点是为了完整性,但不推荐这种方法。将行数相乘只是为了删除它们distinct是低效的。

在许多数据库中,最有效的方法可能是:

select count(*)
from a
where exists (select 1 from b where b.id = a.id) and
      exists (select 1 from c where c.id = a.id);

id注意:这假设列上有索引,并且ida.


推荐阅读