sql表的多行上的布尔逻辑

时间:2011-07-23 17:51:14

标签: mysql sql

假设我有以下数据:

id  name  source
-----------------
1   'n'   'a'
1   'n'   'b'
1   'n'   'c'
1   'n'   'd'    
2   'n'   'a'
2   'n'   'c'

如何选择包含的所有ID(source == a || source == f)&& (source == c || source == g)?

这是针对MySQL ...

2 个答案:

答案 0 :(得分:1)

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')
    )

答案 1 :(得分:0)

编辑:现在已修复)

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)