我有三张桌子:
用户,群组和群组用户
用户表:
id:1个用户名:admin
id:2用户名:barry
小组表:
id:102名称:管理员
id:103名称:网站用户
GroupsUser(用户和组之间的联接表)
id:1 user_id:1 group_id:102
id:2 user_id:2 group_id:103
id:3 user_id:1 group_id:103
现在我遇到的问题是:我想从Users表中选择不属于'Administrator'组的所有用户。我的尝试是这样的:
SELECT COUNT(*) AS `count`
FROM `Users` AS `User`
LEFT JOIN `GroupsUsers` AS `GroupsUser`
ON (`GroupsUser`.`user_id` = `User`.`id` AND `GroupsUser`.`group_id` NOT in ( 102 ) )
WHERE
(
NOT ( `GroupsUser`.`group_id` IN ( 102 )
)
)
出于某种原因,这仍然会返回管理员帐户。我想要做的是返回JUST'barry',或者在这种情况下 - COUNT为'1',而不是'2'。
答案 0 :(得分:3)
SELECT COUNT(*) AS `count`
FROM Users AS User
LEFT JOIN GroupsUsers AS GroupsUser
ON GroupsUser.user_id = User.id AND GroupsUser.group_id = 102
WHERE GroupsUser.user_id IS NULL
左连接尝试在组102(管理员)中的GroupUsers表中查找用户。如果找到匹配项,则GroupsUser.user_id
不为空,因此反向条件WHERE GroupsUser.user_id IS NULL
仅保留在无法找到匹配项的位置,即用户不是管理员。
对于评论“我想选择只在相应表中具有该行的用户”,这既不是问题正文,也不是标题
SELECT COUNT(*) AS `count`
FROM Users AS User
LEFT JOIN GroupsUsers AS GroupsUser1
ON GroupsUser1.user_id = User.id AND GroupsUser1.group_id = 102
LEFT JOIN GroupsUsers AS GroupsUser2
ON GroupsUser2.user_id = User.id AND GroupsUser2.group_id <> 102
WHERE GroupsUser2.user_id IS NULL
答案 1 :(得分:0)
您正在尝试获取仅属于“网站用户”的用户,同时他们不是“管理员”
因此,如果用户属于这两个组,您希望将他从结果中排除......
如果这是你想要做的,试试这个:
SELECT `User`.*
FROM `Users` AS `User`
WHERE `User`.id NOT IN (
SELECT `User2`.id
FROM `Users` AS `User2`, `GroupsUsers` AS `GroupsUser`
WHERE
( `GroupUser`.`user_id` = `User2`.`id` )
AND
( `GroupUser`.`group_id` = 102 )
)
希望这会有所帮助...
祝你的发展好运......