2017-07-03 39 views
0

假設這是一個查詢顯示所有結果與更多然後1項

id   value 
------  --------- 
    10    123 
    10    422 
    11    441 
    11    986 
    12    674 
    13    648 

什麼我需要添加到該查詢返回所有的ID具有與它們相關的2個或多個值的結果。所以,在這種情況下,它只會返回ID 10 & 11,但我需要記錄。

這樣的結果是這樣的:

id   value 
------  --------- 
    10    123 
    10    422 
    11    441 
    11    986 

GROUP BY不會幫我,因爲我只拿到了1回.. ;-)

謝謝。

回答

0

您可以使用exists

select t.* 
from t 
where exists (select 1 from t t2 where t2.id = t.id and t2.value <> t.value); 
1

這裏有一個簡單的方法來做到這一點

select * from table where id in (select id from table group by id having count(id)>1) order by id; 
+0

應該是'IN' ... –

+0

@Prdp謝謝你,我忘了, 「=」當子查詢返回多行時會導致錯誤。同樣修正它。 –

+0

由於某種原因'count(id)> = 2'不適合我的眼睛。我將它寫爲'Count(id)> 1';) –