T
T
the5x2020-02-10 19:50:57
MySQL
the5x, 2020-02-10 19:50:57

How to connect Many to Many correctly?

Tell me how to link three tables so that there is something like this output
username: group1, group2, group3, ...

users:

  • id
  • username


groups:
  • id
  • title


users_groups:
  • id
  • user_id
  • groups_id

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lazy @BojackHorseman MySQL, 2020-02-10
Tag

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question