2012-06-23 69 views
0

我有一個將元素分配給組的表格。每個元素都可以在許多羣體存在,並且可以分配幾次同一組從鏈接表中獲取元素

它看起來像:

element | group 
     1 | 1 
     1 | 2 
     1 | 3 
     2 | 1 
     2 | 3 
     3 | 2 

我在尋找一個簡單的查詢,可以返回我的元素被分配到組1,而不是組2

根據以上這個所呈現的數據將是元件2

回答

2
select distinct element 
from your_table 
where element not in (select element 
         from your_table 
         where `group` = 2) 
and `group` = 1 
+0

它的工作原理。謝謝 –

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