为什么这两个查询会为role
提供不同的结果?
正确结果(角色与用户正确关联):
SELECT
users.*,
activations.id AS activation
(SELECT
roles.name
FROM roles
INNER JOIN role_users ON roles.id = role_users.role_id
WHERE role_users.user_id = users.id
LIMIT 1) AS role
FROM users
LEFT JOIN activations ON users.id = activations.user_id
错误结果(角色始终是roles
表的第一条记录):
SELECT
users.*,
activations.id AS activation
(SELECT
roles.name
FROM roles
INNER JOIN role_users ON roles.id = role_users.role_id
INNER JOIN users ON users.id = role_users.user_id
LIMIT 1) AS role
FROM users
LEFT JOIN activations ON users.id = activations.user_id
我无法使用第一个查询(使用WHERE role_users.user_id = users.id
)而我必须使用第二个查询(使用' JOIN'):如何获得正确的结果?
由于
编辑:回答评论:
I can't use the first query
表示我使用Laravel查询生成器构建它,而在Laravel查询生成器中翻译为WHERE role_users.user_id = users.id
的表达式->where('role_users.user_id', '=', 'users.id')
并不是&#39}因为它被处理为WHERE role_users.user_id = 'users.id'
,所以可以正常工作。
我可以使用whereRaw(),但我想避免这种情况,并寻找更好的解决方案ORDER BY roles.id
)< / LI>
醇>
答案 0 :(得分:0)
您的子查询未加入您的主查询,因此不会将用户绑在一起。试试这个:
SELECT
u.*,
activations.id AS activation
(SELECT
roles.name
FROM roles
INNER JOIN role_users ON roles.id = role_users.role_id
INNER JOIN users u1 ON u1.id = role_users.user_id AND u1.id = u.id
LIMIT 1) AS role
FROM users u
LEFT JOIN activations ON u.id = activations.user_id
答案 1 :(得分:0)
首先使用外部查询中的用户
进行查询SELECT
/
(SELECT
roles.name
FROM roles
INNER JOIN role_users ON roles.id = role_users.role_id
WHERE role_users.user_id = users.id
^^^^ -- external query user_id
LIMIT 1) AS role
FROM users --- you use this user, so each row has a different user_id
LEFT JOIN activations ON users.id = activations.user_id
第二个查询从用户表中选择第一个角色,并且每行都相同。