我有以下表格,我需要在Oracle SQL中进行查询:
T1:
ID (PK)
1
2
3
4
5
6
7
8
T2:
Id T1-ID(FK) Value
1 1 apple
2 2 null
3 2 null
4 3 apple
5 3 null
6 4 apple
7 4 orange
8 4 null
9 5 orange
10 5 null
11 6 orange
12 6 apple
13 7 kiwi
14 8 mango
15 8 apple
16 8 null
如何获取只有apple或null或两者的行。查询不应返回任何具有橙色,奇异果,芒果等的行,即使该ID具有apple或null。
输出:
Id T1-ID(FK) Value
1 1 apple
2 2 null
3 2 null
4 3 apple
5 3 null
答案 0 :(得分:0)
以下是使用sub-query
和GROUP_CONCAT
的解决方案。
SELECT *
FROM T2
WHERE `T1-ID` IN
(SELECT
`T1-ID`
FROM T2
GROUP BY `T1-ID`
HAVING 'apple' = GROUP_CONCAT(DISTINCT Value))
答案 1 :(得分:0)
select t.*
from t2 t
where (t.value = 'apple' or t.value is null)
and not exists (select 1
from t2 x
where x.t1_id = t.t1_id
and x.value <> 'apple')
order by t.id;
SQLFiddle示例:http://sqlfiddle.com/#!15/a9f28/1