在SQL中结合WHERE EXISTS和IN

时间:2019-03-07 08:45:44

标签: sql db2 exists relational-division

考虑表中有n行带有名称和特殊性的

NAME SPECIALITY
AA     X
AA     Y
BB     X
CC     X
CC     Y
CC     Z

我需要使用专业名称包括X和Y的名称。因此,我应该获得AA和CC。 我遇到了存在的地方,但我还没有正确地构架它:

SELECT DISTINCT NAME
FROM SAMPLE
WHERE EXISTS (
    SELECT SPECIALITY
    FROM SAMPLE
    WHERE SPECIALITY IN ('X','Y')
);

这将显示所有名称。我无法破解。你能帮忙理解吗?

6 个答案:

答案 0 :(得分:1)

使用聚合

select name 
from tab
where SPECIALITY in ('X','Y')
group by name
having count(distinct SPECIALITY)=2

在您的查询中,我可以进行如下修改

SELECT DISTINCT NAME
FROM SAMPLE t1
WHERE EXISTS (SELECT SPECIALITY  FROM 
             SAMPLE t2
             WHERE SPECIALITY IN ('X','Y') and
             t1.NAME=t2.NAME 
             having count(distinct SPECIALITY)=2
            );

答案 1 :(得分:0)

您可以像以下方式使用self join

select distinct t1.NAME from SAMPLE t1 join SAMPLE t2
on t1.NAME = t2.NAME 
and t1.SPECIALITY = 'X' and t2.SPECIALITY = 'Y'

答案 2 :(得分:0)

您可以在表上进行简单的self join来获取所需的输出,如下所示。

SELECT t1.NAME 
FROM   yourtable t1 
       INNER JOIN yourtable t2 
               ON t1.NAME = t2.NAME 
WHERE  t1.speciality = 'x' 
       AND t2.speciality = 'y' 

以上查询将显示同时具有names specialityx的所有y

答案 3 :(得分:0)

您可以像这样使用EXISTS

SELECT name
FROM sample AS tx
WHERE speciality = 'x'
AND EXISTS (
    SELECT 1
    FROM sample AS ty
    WHERE ty.name = tx.name
    AND ty.speciality = 'y'
)

它将找到存在x行的所有y行。

答案 4 :(得分:0)

EXISTS版本需要两个EXISTS

SELECT S.*
FROM SAMPLE S
WHERE EXISTS (SELECT 1 FROM SAMPLE S1 WHERE S.NAME = S1.NAME AND S1.SPECIALITY = 'X') AND
      EXISTS (SELECT 1 FROM SAMPLE S1 WHERE S.NAME = S1.NAME AND S1.SPECIALITY = 'Y');

但是,简单的聚合也应该有效:

SELECT S.NAME
FROM SAMPLE S
WHERE SPECIALITY IN ('X', 'Y')
GROUP BY NAME
HAVING MIN(SPECIALITY) <> MAX(SPECIALITY);

答案 5 :(得分:0)

您需要的关系运算符称为divide,也就是提供所有零件的供应商。

SQL没有除法运算符,因此您必须根据自己的喜好来决定是否使用除法运算符。

但是,如果您只有两个硬编码的值,则可以简化很多事情:

SELECT NAME FROM SAMPLE WHERE SPECIALITY IN = 'X'
INTERSECT
SELECT NAME FROM SAMPLE WHERE SPECIALITY IN = 'Y'