我在MySQL中有4个表
用户
USER_INFO
USER_RIGHTS
101 =读右:
102 =写得正确
103 =删除权利
组
现在,当我想选择使用INNER JOIN的所有用户时,我会执行类似
的操作SELECT users.id, user_info.first_name, user_info.last_name, user_rights.right
FROM `users`
INNER
JOIN user_info
ON users.id = user_info.user_id
ORDER BY user_info.first_name;
我得到2个用户。
我想创建另一个INNER JOIN,例如选择在组1中拥有权限的成员,但我的代码不起作用......
SELECT users.id, user_info.first_name, user_info.last_name, user_rights.right
FROM `users`
INNER
JOIN user_info
ON users.id = user_info.user_id
INNER
JOIN user_rights
ON user_rights.rights = '101'
ORDER BY user_info.first_name;
这个想法是选择成员在某个组中具有READ权限的成员。希望我能说清楚。
答案 0 :(得分:4)
SELECT users.id, user_info.first_name, user_info.last_name, user_rights.right
FROM `users`
INNER
JOIN user_info
ON users.id = user_info.user_id
INNER
JOIN user_rights
ON user_rights.user_id = users.id
INNER JOIN groups
on groups.id = user_rights.group
where user_rights.right = '101'
and groups.group_name = 'Human Resources'
ORDER BY user_info.first_name;
答案 1 :(得分:1)
您必须使用组表添加联接:
SELECT users.id, user_info.first_name, user_info.last_name, user_rights.right
FROM `users`
INNER
JOIN user_info
ON users.id = user_info.user_id
INNER
JOIN user_rights
ON user_rights.user_id = users.id
INNER
JOIN groups
ON user_rights.group = groups.id
WHERE user_rights.rights = '101' AND groups.group_name = 'Human Resources'
答案 2 :(得分:0)
使用Left Join with User_Rights获取所有用户和权限
SELECT users.id,
user_info.first_name,
user_info.last_name,
user_rights.right
FROM users
INNER JOIN user_info
ON users.id = user_info.user_id
LEFT JOIN user_rights
ON user_rights.user_id = users.id
AND user_rights.right = '101'
LEFT JOIN GROUPS
ON user_rights.group = GROUPS.group
AND groups.group_name = 'Human Resources'
ORDER BY user_info.first_name;