[英]Howto Select rows that match the intersection of multiple rows in other tables in MYSQL?
[英]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中執行此操作。
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子句只過濾掉那些。
實現這一目標的最簡單方法可能是在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')
這適用於Microsoft SQL-Server; 但是,這應該在MySQL上不加修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.