开发者

boolean logic on multiple rows of an sql table

supposing I have the following data:

开发者_StackOverflow中文版
id  name  source
-----------------
1   'n'   'a'
1   'n'   'b'
1   'n'   'c'
1   'n'   'd'    
2   'n'   'a'
2   'n'   'c'

How can I select all ids that contain (source==a || source==f) && (source==c || source==g) ?

This is for MySQL...


select unique id from table as t1
where (t1.source = 'a' or t1.source='f')
  and exists 
   (select * from table as t2
    where t2.id = t1.id and (t2.source = 'c' or t2.source='g')
    )


(edit: it's fixed now)

select id
from
    (select id
    from table
    where source = 'a' or source = 'f'
    group by id) as t1
join
    (select id
    from table
    where source = 'c' or source = 'g'
    group by id) as t2
using (id)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜