Domanda

I have 2 tables that gets joined in a 3 table, so that there is a many to many relationship, and I am trying to get all users and show them once, but with all the users user groups

Users
- user_id
- email

groups
- group_id
- broup_name

users_groups
- users_groups_id
- user_id
- group_id

I am trying to get all the users and display each user once, but with all the users user groups, like shown here:

some@user.dk - admin, moderator, public
another@user.dk - moderator, public

Is it even possible to select the data like this or do you have to sort it in the code instead?

È stato utile?

Soluzione

Yes, it's possible. It's even easy.

SELECT email, GROUP_CONCAT(DISTINCT group_name ORDER BY g.group_id) AS groups
  FROM Users AS u
  JOIN users_groups AS ug ON u.user_id = ug.user_id
  JOIN Groups AS g on ug.group_id = g.group_id
 GROUP BY email
 ORDER BY email

That will display one line per email, with the distinct groups belonging to that user shown in order of group id. T

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top