我将用户和组表设置如下。
users
id int
groups
id int
users_groups
user_id int
group_id int
示例数据:
+---------+----------+
| user_id | group_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 2 |
| 3 | 3 |
| 4 | 1 |
| 4 | 2 |
| 5 | 2 |
+---------+----------+
有没有办法选择不在给定组中的所有用户?我尝试加入users
和users_groups
表并添加一个,比方说group_id != 1
条件,但是当用户在另一个组中时,我最终会得到用户,例如用户[1,3 ,3,4,5]。
因此,当我说我希望不在给定组中的用户group_id != 1
时,示例结果应该是用户[3,5]。
答案 0 :(得分:4)
选择不在特定群组中的用户ID的最简单方法是使用NOT IN
:
SELECT id
FROM users
WHERE id NOT IN (SELECT user_id FROM users_groups WHERE group_id = 1)
其他常用的替代方案是NOT EXISTS
:
SELECT id
FROM users
WHERE NOT EXISTS (
SELECT NULL
FROM users_groups
WHERE group_id = 1
AND user_id = users.id
)
LEFT JOIN / IS NULL
:
SELECT id
FROM users
LEFT JOIN users_groups
ON users.id = users_groups.user_id
AND users_groups.group_id = 1
WHERE users_groups.user_id IS NULL
答案 1 :(得分:2)
试试这个:
SELECT * FROM users WHERE id
NOT IN (SELECT user_id FROM users_groups WHERE group_id = 1)
答案 2 :(得分:1)
您可以使用以下查询:
Select Users.*
from Users
where id in
(Select user_id from users_groups where group_id <> given_group_id)
答案 3 :(得分:0)
SELECT a.* FROM users AS a
LEFT JOIN users_groups AS b ON b.user_id=a.id
WHERE b.group_id!=1
GROUP BY a.id
关键字为GROUP BY
答案 4 :(得分:0)
试试这个:
SELECT *
FROM users u
LEFT OUTER JOIN users_groups ug ON ug.user_id = u.user_id
AND ug.group_id =1
WHERE ug.user_id IS NULL
答案 5 :(得分:-1)
在这种情况下,我会使用“WHERE NOT EXIST”语句。