我有下表:
+-------------------+
| Id | G_id | E_id |
+-------------------+
| 1 | 1 | 1 |
---------------------
| 2 | 1 | 2 |
---------------------
| 3 | 2 | 1 |
---------------------
| 4 | 2 | 3 |
---------------------
| 5 | 3 | 1 |
---------------------
| 6 | 3 | 2 |
---------------------
| 7 | 3 | 3 |
+-------------------+
其中G_id是一个组的id,包含由其E_id标识的多个元素。例如,第1组由元素1和2,元素1和3的第2组以及元素1,2和3的第3组组成。
我想对此表进行查询,以便返回至少包含元素1和3的所有组,即组2和3.谢谢!
答案 0 :(得分:2)
您需要Group By
和Having
子句
select G_id
from yourtable
where E_id in (1,3)
group by G_id
having count(distinct E_id) = 2
更新:
select G_id
from yourtable
group by G_id
having count(case when E_id = 1 then 1 end) > 0
and count(case when E_id = 3 then 1 end) > 0
and count(distinct E_id) = 3