I have the following database tables :
user
int unsigned id
varchar login
group
int unsigned id
varchar label
right
int unsigned id
varchar label
user_group
int unsigned userId
int unsigned groupId
user_right
int unsigned userId
int unsigned rightId
group_right
int unsigned groupId
int unsigned rightId
A right is considered as granted to a group or a user when it’s associated using user_right or group_right tables (respectivly).
I have the following query that is supposed to retrieve an user’s rights from his login :
SELECT DISTINCT `R`.`id`,
`R`.`label`
FROM `user` `U`,
`right` `R`,
`user_right` `UR`,
`user_group` `UG`,
`group_right` `GR`
WHERE (`U`.`id` = `UR`.`userId`
AND `R`.`id` = `UR`.`rightId`
OR `U`.`id` = `UG`.`userId`
AND `UG`.`groupId` = `GR`.`groupId`
AND `R`.`id` = `GR`.`rightId`)
AND `U`.`login` = 'admin'
When a user is associated to rights and groups, the query does work and returns the right rights. But when a user has no group, the query does not work. If i remove the unused tables (user_group and group_rights), it does work again.
What should i add to my query to avoid this ? Should I add something like “OR some_column IS NULL” ? I’d appreciate if you could also explain me why so i don’t meet this problem again.
Thanks in advance.
Some sample datas :
user (id, login)
1 'admin'
right (id, label)
1 'r1',
2 'r2',
3 'r3'
user_right (id, label)
1 1
Thanks for reading 🙂
First of all, you are using implicit joins, and, the way you wrote your query, they are
INNER JOINs. You should change your query to use proper explicit joins, and useLEFT JOINs in there. Something like this: