我想从我的数据库中选择所有以@gmail.com结尾的电子邮件结束的用户,这些邮件还没有在groupID 4的组中。
问题是我的user_to_group表如下所示:
userID | groupID
--------------------
1 | 5
1 | 4
1 | 3
2 | 3
2 | 6使用groupID 4的用户被排除在外,但是由于他们也在其他组中,无论如何他们都会被选中。在本例中,我只需要使用userID 2的用户。
是否有可能将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"发布于 2013-12-17 14:46:05
是的,您可以使用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
)发布于 2013-12-17 14:46:18
这是使用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';https://stackoverflow.com/questions/20637106
复制相似问题