如果所有值均符合条件,则返回

时间:2019-07-10 23:05:51

标签: sql oracle

我试图返回在子表中具有所有符合条件的记录的所有行

T1:
1
2
3
4
5

T2:

T.ID  Id  Value
1     01  Apple
1     02  Banana
2     05  Grapes
2     07  Kiwi
2     08  Apple
3     04  Banana
3     06  Potato
4     10  Honeydew
4     11  Berries
5     14  Apple
5     15  Kiwi
5     16  Radish

我需要识别T1中的所有ID,它们是T2中的Fruit, T2.value(苹果,葡萄,香蕉,奇异果,蜜瓜,浆果)
所需的输出:

1
2
4

我已经尝试过了:

select t1.id from t1,t2
where t1.id = t2.id
and t2.value  in ('Apple','Grapes','Banana','Kiwi','Honeydew','Berries') 

但它不会返回我需要的输出,它还会返回#3&5。

3 个答案:

答案 0 :(得分:1)

显然,您要尝试的是消除包含不是个水果的项目的组:

SELECT T1.ID
  FROM T1
  WHERE T1.ID NOT IN (SELECT T2.T1_ID
                        FROM T2
                        WHERE T2.VALUE NOT IN ('Apple','Grapes','Banana','Kiwi','Honeydew','Berries'))
  ORDER BY T1.ID

dbfiddle here

答案 1 :(得分:1)

假设您希望ID在t2中有至少一行

select t2.id
from t2
group by t2.id
having sum(case when t2.value not in ('Apple', 'Grapes', 'Banana', 'Kiwi', 'Honeydew', 'Berries')
                then 1 else 0
           end) = 0;  -- nothing that isn't fruit

答案 2 :(得分:0)

在此处添加一个可能的答案。

在这种情况下,您可以使用EXISTS

SELECT
    T1.ID
FROM
    T1
WHERE
    NOT EXISTS (
        SELECT
            1
        FROM
            T2
        WHERE
            T2.T1_ID = T1.ID
            AND T2.VALUE NOT IN (
                'Apple',
                'Grapes',
                'Banana',
                'Kiwi',
                'Honeydew',
                'Berries'
            )
    )

db<>fiddle demo

干杯!