I need to get a list of users with its highest role name. Due to some circumstances one user has just one role. So I have some users with the same
CONCAT(first_name, last_name)
but with different ids. Highest role can be simply found just sorting all the user's roles in ascending order and getting just the first one. Thus I decided to use correlated subquery to get highest role id for appropriate user.
But on executing the following query
SELECT
u.id AS UserID,
u.user_name AS UserName,
u.user_hash AS Hash,
u.first_name AS FirstName,
u.last_name AS LastName,
u.phone_mobile AS PhoneMobile,
u.address_city AS City,
u.address_state AS State,
ar.name AS RoleName
FROM
users AS u
JOIN
acl_roles_users AS aru ON (u.id = aru.user_id AND aru.deleted = 0)
JOIN
acl_roles AS ar ON aru.role_id = ar.id
JOIN
(SELECT
ar2.id AS RoleID
FROM
users AS u2
JOIN acl_roles_users AS aru2 ON (u2.id = aru2.user_id
and aru2.deleted = 0)
JOIN acl_roles AS ar2 ON (aru2.role_id = ar2.id
AND ar2.deleted = 0)
WHERE
concat(u2.first_name, u2.last_name) = concat(u.first_name, u.last_name)
ORDER BY ar2.name ASC
LIMIT 1) AS temptbl ON RoleID = ar.id
WHERE
u.status = 'Active' and u.deleted = 0
ORDER BY UserName
LIMIT 1000000;
I get an error message
Error Code: 1054. Unknown column 'u.first_name' in 'where clause'
Why 'u' (users) table is not resolved in subquery? Are there any ideas how to rewrite query?