我想弄清楚查询结果是否包含一些项目。我解释: 我有一个profile_stores表,其中包含每个配置文件的托管商店 假设我有5个配置文件P1-> P5和4存储s1 - > S4 我的表包含
profie | store
------------------
P1 | S1
P2 | S2
P3 | S3
P2 | S2
P1 | S2
P1 | S3
P4 | S1
P5 | S2
现在,我们有以下配置文件1 P1正在管理商店S1和S2以及S3
=>
P1(S1,S2,S3)
P2(S1,S2)
P3(S4)
P4(S1)
P5(S2)
我现在需要知道的是如何设置查询以获取同时管理的配置文件以及仅存储S1和S2的配置文件?
Ps:在我的情况下,查询应该只返回P2
任何帮助将不胜感激
答案 0 :(得分:2)
GROUP BY
- 溶液:
select profile
from tablename
group by profile
having count(distinct store) = 2
and min(store) = 'S1'
and max(store) = 'S2'
替代解决方案:
select profile
from tablename t1
where not exists (select 1 from tablename t2
where t1.profile = t2.profile
and t2.store not in ('S1', 'S2', ...))
group by profile
having count(distinct store) = 2 (or 3 or 4...)
答案 1 :(得分:0)
另一种方法
select profile from table where store = 's1'
intersection
select profile from table where store = 's2'
except
select profile from table where store not in ('s1', 's2')