[英]sql join with foreign key table
我想從數據庫中選擇所有以@gmail.com
結尾的電子郵件的用戶,這些用戶尚未在組groupID
4的組中。
問題是我的user_to_group
表看起來像這樣:
userID | groupID
--------------------
1 | 5
1 | 4
1 | 3
2 | 3
2 | 6
排除了具有groupID
4的用戶,但是由於它們也位於其他組中,因此無論如何都將選擇它們。 在此示例中,我只需要具有userID
2的userID
。
是否可以排除第4組中的用戶,而與其他組無關?
SELECT * FROM wcf13_user user_table
RIGHT JOIN wcf13_user_to_group ON (wcf13_user_to_group.userID = user_table.userID && groupID != 4 )
WHERE user_table.email LIKE "%@gmail.com"
是的,您可以使用EXISTS
子查詢來執行此操作:
SELECT *
FROM wcf13_user user_table u
WHERE user_table.email LIKE "%@gmail.com" -- Has a gmail account
AND NOT EXISTS ( -- Is not a member of group #4
SELECT *
FROM wcf13_user_to_group g
WHERE u.userID=g.userID AND groupID = 4
)
這是使用not exists
子句的好地方:
SELECT ut.*
FROM wcf13_user ut
WHERE not exists (select 1
from wcf13_user_to_group utg
where utg.userID = ut.userID and utggroupID = 4
) and
ut.email LIKE '%@gmail.com';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.