How to associate Many to Many?

Tell me how to link the three tables to such a conclusion
username: group1, group2, group3,...

users:
  • id
  • username


groups:
  • id
  • title


users_groups:
  • id
  • user_id
  • groups_id
April 7th 20 at 11:02
1 answer
April 7th 20 at 11:04
SELECT
 CONCAT((SELECT u.`username` FROM `users` u WHERE u.`id` = t.`user_id`), ': ', t.`_groups`)
FROM (
 SELECT 
 ug.`user_id`, GROUP_CONCAT(g.`title` SEPARATOR ', ') AS _groups
 FROM `users_groups` ug
 JOIN `groups` g ON g.`id` = ug.`groups_id`
 GROUP BY ug.`user_id`
) t
SELECT
 u.username AS username,
 GROUP_CONCAT(g.title) as "groups"
FROM users u
JOIN users_groups ug ON u.id = ug.user_id
JOIN `groups` g ON g.id = ug.group_id
GROUP BY u.username


? - rita66 commented on April 7th 20 at 11:07

Find more questions by tags MySQLSQL