Created
December 15, 2016 16:16
-
-
Save kshep92/d1ae4dbef40577effece406a387460d7 to your computer and use it in GitHub Desktop.
Using MySQL GROUP_CONCAT to fetch pesky many-to-many relationships in one go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| id | name | email | permissions | | |
|----|-------|----------------|--------------------| | |
| 1 | kevin | kevin@mail.com | basic,manage_posts | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
select u.*, group_concat(perms.permission_id) as permissions | |
from users u, users_permissions perms | |
where u.id = perms.user_id | |
and u.id = 1 | |
group by u.id; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE `users` ( | |
`id` int auto_increment primary key, | |
`name` varchar(50), | |
`email` varchar(50) | |
); | |
create table permissions ( | |
id varchar(50) primary key, | |
label varchar(50) | |
); | |
create table users_permissions( | |
user_id int, | |
permission_id varchar(50), | |
primary key(user_id, permission_id) | |
); | |
insert into users values (1, 'kevin', 'kevin@mail.com'); | |
insert into permissions values | |
('basic', 'Basic permissions'), | |
('manage_posts', 'Manage posts'), | |
('view_finances', 'View financial data'); | |
insert into users_permissions values | |
(1, 'basic'), | |
(1, 'manage_posts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment