SQL 使用条件对同一表进行两次查询

  • 本文关键字:查询 两次 条件 SQL sql
  • 更新时间 :
  • 英文 :


>我有 1 张桌子

表包含类似以下内容的内容:

ID, parent_item, Comp_item
1, 123, a
2, 123, b
3, 123, c
4, 456, a
5, 456, b
6, 456, d
7, 789, b
8, 789, c
9, 789, d
10, a, a
11, b, b
12, c, c
13, d, d

我只需要返回 a 和 b Comp_item的parent_items 所以我应该只得到:

123
456

这是执行此操作的规范方法:

SELECT parent_item
FROM yourTable
WHERE Comp_item IN ('a', 'b')
GROUP BY parent_item
HAVING COUNT(DISTINCT Comp_item) = 2

这里的想法是用parent_item聚合,限制为只有Comp_itemab的记录,然后断言Comp_item值的不同数量是2。

或者你可以使用INTERSECT

select parent_item from my_table where comp_item = 'a'
intersect
select parent_item from my_table where comp_item = 'b';

如果您有父项表,最有效的方法可能是:

select p.*
from parent_items p
where exists (select 1 from t1 where t1.parent_id = p.parent_id and t1.comp_item = 'a') and
exists (select 1 from t1 where t1.parent_id = p.parent_id and t1.comp_item = 'b');

为了获得最佳性能,您需要在t1(parent_id, comp_item)上建立索引。

我应该强调的是,我非常喜欢 Tim 的聚合解决方案。 我提出这个是因为性能是在评论中提出的。intersectgroup by都花费聚合工作(在第一种情况下删除重复项,在第二种情况下显式删除(。 像这样的方法不会产生这种成本 - 假设具有唯一父 ID 的表可用。

最新更新