我试图在多个条件下从连接中获取一些id-s。 例 加入等后
A B
x 1
x 2
x 3
y 1
y 2
y 3
y 5
z 1
z 5
所以我想要那些id-s(A),例如B是1,也是5
所以结果是y,z
由于
答案 0 :(得分:3)
使用两个EXISTS
可能看起来更干净:
SELECT DISTINCT A
FROM Table1 t1
WHERE EXISTS(SELECT A FROM Table1 WHERE A = t1.A and B = 1)
AND EXISTS(SELECT A FROM Table1 WHERE A = t1.A and B = 5)
答案 1 :(得分:1)
您可以通过WHERE和GROUP + HAVING实现此目的,HAVING
将确保满足2个条件。
SELECT T1.A
FROM Table1 AS T1
JOIN Table2 AS T2
ON T2.ID = T1.ID
WHERE T2.B IN(1,5)
GROUP BY T1.A
HAVING COUNT(*) = 2
或者,对于相同的A,如果B可能有1行或5行,则可以这样做:
SELECT DISTINCT T1.A
FROM Table1 AS T1
JOIN Table2 AS T2
ON T2.ID = T1.ID
AND T2.B = 1
JOIN Table2 AS T3
ON T3.ID = T1.ID
AND T3.B = 5
答案 2 :(得分:1)
select A from Table group by A
having max(decode(B,1,0)) + max(decode(B,5,0)) = 0
答案 3 :(得分:1)
如果条件是"不同"在某个意义上,给定的行只能满足条件的一个,那么可以使用类似的东西:
select a
from table1
group by a
having count(
case
when b = 1 then 1
when b = 5 then 1
end
) = 2
order by a
在案例结构中设置每个条件,并测试计数是否等于条件数。
或者类似于Egor Skriptunoff的方法:
select a
from table1
group by a
having max(case when b=1 then 1 end)=1
and max(case when b=5 then 1 end)=1
order by a
每种条件下的最大值()。
两种方法都不需要自联接。