我有一个表格,可以为组分配元素。每个元素可以存在于多个组中,并且可以分配几次到同一组
看起来像:
element | group
1 | 1
1 | 2
1 | 3
2 | 1
2 | 3
3 | 2
我正在寻找一个简单的查询,它可以返回分配给组1但不归属于组2的元素。
根据上面提供的数据,这将是元素2.
答案 0 :(得分:2)
select distinct element
from your_table
where element not in (select element
from your_table
where `group` = 2)
and `group` = 1
答案 1 :(得分:0)
SELECT *
FROM `table` t1
LEFT OUTER JOIN `table` t2
ON t1.element = t2.element
AND t2.`group` = 2
WHERE t1.`group` = 1
AND t2.`group` IS NULL
答案 2 :(得分:0)
就像那样:
select element from table
where group = 1 and not exists
(select element from table t
where t.element=table.element and t.group = 2)