我有用户和权限表。它们之间的关系是:
一个用户HAS MANY
权限。
我需要让所有没有权限的用户hide
。
例如,users表具有:
id ¦ name ¦ email ¦ password
---+ -------+-----------------+----------
1 ¦ Test 1 ¦ test@gmail.com ¦ 1234
2 ¦ Test 2 ¦ test2@gmail.com ¦ 2345
3 ¦ Test 3 ¦ test3@gmail.com ¦ 2345
4 ¦ Test 4 ¦ test4@gmail.com ¦ 8888
5 ¦ Test 5 ¦ test5@gmail.com ¦ 9876
和权限表如下所示:
user_id ¦ permission
---------+------------
1 ¦ read
2 ¦ edit
2 ¦ hide
4 ¦ edit
5 ¦ hide
这是我到目前为止所尝试的:
SELECT *
FROM users
LEFT JOIN permissions
ON users.id = permissions.user_id
AND permissions.permission != 'hide'
但这仍然让我第二个用户,因为第二个用户也有权限编辑。
预期结果:
id ¦ name ¦ email ¦ password ¦ permission
---+ -------+-----------------+---------- +------------
1 ¦ Test 1 ¦ test@gmail.com ¦ 1234 ¦ read
3 ¦ Test 3 ¦ test3@gmail.com ¦ 2345 ¦ null
4 ¦ Test 4 ¦ test4@gmail.com ¦ 8888 ¦ edit
这里最好的方法是什么?
答案 0 :(得分:1)
not exists
SELECT *
FROM users u
left JOIN permissions p
ON u.id = p.user_id
where not exists ( select 1
from permissions p2
where p2.user_id = u.id
and p2.permission = 'hide'
)
答案 1 :(得分:0)
SELECT *
FROM users u
left JOIN permissions p
ON u.id = p.id
where u.id not in
(
select id
from permissions
where permission = 'hide'
group by id
)
输出
id Name Email Password id permission
1 Test 1 test@gmail.com 1234 1 read
3 Test 3 test3@gmail.com 2345 (null) (null)
答案 2 :(得分:0)
一个可能的答案可能是
select * from Users U
inner join Permissions P on P.id=U.id
WHere U.id NOT IN (SELECT U.ID FROM Users U
inner join Permissions P on P.id=U.id
WHere P.Permission ='HIDE')
1)这将返回具有隐藏权限的ID
SELECT U.ID FROM Users U
inner join Permissions P on P.id=U.id
WHere P.Permission ='HIDE'
2)这将返回除上述返回的ID之外的所有数据,这将是您预期的
select * from Users U
inner join Permissions P on P.id=U.id
WHere U.id NOT IN (SELECT U.ID FROM Users U
inner join Permissions P on P.id=U.id
WHere P.Permission ='HIDE')