我需要约束有关用户角色(用户或管理员)的用户查询。
在数据库中有一个表user_scope
,其中包含所有用户ID和分配的角色(每个用户都有一个条目,其中1表示用户,有些条目有第二个条目,2表示管理员)。我现在无法改变这种数据库架构。
到目前为止,这是我在表users
上的SELECT,它连接来自其他表的数据
SELECT
u.id,
GROUP_CONCAT(DISTINCT scopes.scope ORDER BY scopes.id ASC SEPARATOR ' ') as scope
FROM users as u
LEFT JOIN user_scope on user_scope.user_id = u.id
LEFT JOIN scopes on scopes.id = user_scope.scope_id
表users
+----+--------+
| id | parent |
+----+--------+
| 1 | Alex |
| 2 | Marc |
| 3 | Cath |
+----+--------+
表user_scope
+---------+----------+
| user_id | scope_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
+---------+----------+
表scopes
+----+--------+
| id | scope |
+----+--------+
| 1 | user |
| 2 | admin |
+----+--------+
这将产生类似这样的东西
+----+------------+
| id | scope |
+----+------------+
| 1 | user admin |
| 2 | user |
| 3 | user |
+----+------------+
当我想根据一个特定角色过滤结果时,会出现问题。我试过这个
SELECT
u.id,
GROUP_CONCAT(DISTINCT scopes.scope ORDER BY scopes.id ASC SEPARATOR ' ') as scope
FROM users as u
LEFT JOIN user_scope on user_scope.user_id = u.id
LEFT JOIN scopes on scopes.id = user_scope.scope_id and scopes.id = 2
或分别为1。但是,这不会减少返回行的数量,但只会使用不具有范围admin
的用户的行为NULL。我也尝试使用CASE
,但我不能在WHERE语句中使用它。
如何减少此上下文中返回的行?非常感谢帮助。
答案 0 :(得分:1)
使用having
子句:
SELECT u.id,
GROUP_CONCAT(DISTINCT s.scope ORDER BY s.id ASC SEPARATOR ' ') as scopes
FROM users u LEFT JOIN
user_scope us
ON us.user_id = u.id LEFT JOIN
scopes s
ON s.id = us.scope_id
GROUP BY u.id
HAVING MAX(s.id = 2) > 0;