ManyToMany query question
I have three simple tables: groups, permissions and group_permissions on a ManyToMany basis. My problem is in performing a query that, given the group id (pk), will retrive a resultset with all permissions, including the ones associated with the given group and the ones not associated with the group.
I have tried something like:
SELECT *
FROM permission
LEFT JOIN group_permissions ON group_permissions.permission_id = permission.id
LEFT JOIN group ON group_permissions.group_id = group.id
WHERE group.id = 123
but it just dont work...
Any sugestions?
Thank you all for the answears, i just resolved my problem in less than 30 minuts! Isn't this something?
SELECT *
FROM auth_permission
LEFT JOIN auth_group_permissions ON auth_group_permissions.permission_id = auth_permission.id AND auth_group_permissions.group_id =开发者_运维知识库 123
LEFT JOIN auth_group ON auth_group.id = auth_group_permissions.group_id
As mentioned in the various comments, you cannot test the value of group.id in the WHERE clause as it will negate the LEFT JOIN and force it to behave like an INNER JOIN.
Instead, make that test part of the JOIN condition:
SELECT *
FROM permission
LEFT JOIN group_permissions
ON group_permissions.permission_id = permission.id
LEFT JOIN `group`
ON group_permissions.group_id = `group`.id
AND `group`.id = 123
group
is a keyword in SQL. It's not generally a good idea to have a table or field named using a keyword, but if you have to, then you must enclose them in the backtick character usually found in the top-left hand corner of the keyboard, under the escape key:
SELECT *
FROM permission
LEFT JOIN group_permissions ON group_permissions.permission_id = permission.id
LEFT JOIN `group` ON group_permissions.group_id = `group`.id
What's the group id being used to specify? If you're not filtering using it, what does it need to be specified for?
精彩评论