ID, Val
的值如下:
1,2
1,NULL
2,NULL
3,2
我怎样才能获得
1,2
2,null
3,2
表示使用val = 2
获取所有行,或者如果行的ID不包含任何Val = 2
答案 0 :(得分:3)
我解释“获取val = 2的所有行,或者如果具有不具有任何Val = 2的ID的行”,则:
select * from table x
where x.val = 2
or not exists (select 1 from table where id = x.id and val = 2)
答案 1 :(得分:0)
尝试:
select t.id, t2.val
from (select distinct id from myTable) t
left join myTable t2 on t.id=t2.id and t2.val=2
SQLFiddle here。
答案 2 :(得分:0)
SELECT DISTINCT *
FROM `table`
WHERE `Val` = 2
OR ( `ID` = 2 AND ( `Val` != 2 OR `Val` IS NULL ) )