L
L
Lavrov952020-08-23 17:03:31
SQL
Lavrov95, 2020-08-23 17:03:31

How to write many to many sql script?

How to write many to many sql script?

students

id | name

classes

id | name

student_classes

id | student_id | class_id

The result should be like this

id | name | classes

1  | Bob  | Class 1, Class 2
2  | Sara | Class 2
3  | Jon  | -

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-08-23
@gebrak

LEFT JOIN and GROUP_CONCAT if mysql
https://www.mysqltutorial.org/mysql-group_concat/

SELECT s.id, s.name, GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') as classes 
FROM students s
LEFT JOIN student_classes sc ON sc.student_id = s.id
LEFT JOIN classes c ON c.id = sc.class_id
GROUP BY s.name
ORDER BY s.id ASC;

Similar for PostgreSQL, only the STRING_AGG function https://www.postgresqltutorial.com/postgresql-aggr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question