2012-10-19 86 views
3

我有一張表,看起來像。mysql select match multiple rows

user project 
---- ------- 
bob  news 
bob  theatre 
sarah news 
fred news 
fred fred 
fred movies 
sarah movies 

我試圖拉的項目清單,如果用戶是從未fred

所以基於上述表中的結果將是。

bob theatre 

我對如何實現這一點很着迷。我可以加入另一個表中的唯一用戶列表。我可以用某種語言的for循環做到這一點,但我認爲必須有一種方法可以在本地sql中執行此操作。

回答

0
select distinct a.* 
from mytable a 
left join mytable b on b.project = a.project and b.user = 'fred' 
where b.user is null 

對於要行,有不會是參加行和這樣的行會null值,因此在where子句過濾掉只是那些。

+0

不錯!這樣可行。我會接受這個答案。我想我甚至會明白它爲什麼起作用。我正在嘗試類似的東西沒有零部分。 – user1757914

0

最簡單的方法是在WHERE語句中使用NOT EXISTS運算符;是這樣的:

Select P.* from Projects P Where NOT EXISTS (Select * from Projects P2 where P2.project = P.project and P2.user = 'fred') 

第二種可能性是使用NOT IN操作符:

Select P.* from Projects P Where P.project NOT IN (Select P2.project from Projects P2 where P2.user = 'fred') 

這是微軟的SQL服務器;但是,這應該在MySQL上未修改運行。

+0

'exists()'表現不好。只有在必須時才使用它 - 連接通常是首選。雖然,我授予你他們更容易理解 – Bohemian

+0

我同意你的觀點,當使用EXISTS()時,性能並不總是最好的,但我不認爲這會在這種類型的數據中引起關注。 – SylvainL