Alias with Join in MySQL and PHP
I'm having some issues with a many to many relationship with a simple ACL module I'm developing.
I have three tables:
Groups
- *id_group
- name
Permissions
- *id_permission
- name
RelPermissionsGroup
- *id_relation
- group
- permission
So I had this query
SELECT * FROM acl_groups
LEFT OUTER JOIN acl_RelPermissionsGroup
ON acl_groups.id_group = acl_R开发者_开发技巧elPermissionsGroup.group
LEFT OUTER JOIN acl_permissions
ON acl_permissions.id_permission = acl_RelPermissionsGroup.permission
WHERE id_group > 0
If I do the query in phpmyadmin it shows fine. So, it shows all groups whether they have permissions or not and if they have it also shows them.
I see one problem here and it is that the name attribute is repeated. How can I alias every single field? But that's not the problem.
The problem is that doing mysqli_fetch_assoc performs fine except for the group that doesn't have any permissions. This is what outputs:
Array (
[id_group] => 2
[name] =>
[id_relation] =>
[group] =>
[permission] =>
[id_permission] =>
)
The group ID is fine but given the fact that fields are duplicated it overrides them. Also, id_group and id_permission seems to be duplicated with group and permission respectively.
What should I do?
You will have to name the fields explicitly, like so
SELECT
ag.name as group_name
,ap.name as permission_name
,ar.`group` as permission_group_id
FROM acl_groups ag
LEFT OUTER JOIN acl_RelPermissionsGroup ar ON ag.id_group = ar.`group`
LEFT OUTER JOIN acl_permissions ap ON ap.id_permission = ar.permission
WHERE id_group > 0
Don't forget that group
is a reserved word and needs to be quoted in backticks `group`
like so.
You should write 'SELECT groups.id_group group_id, groups.name as group_name ...'
精彩评论