I have 2 table in the database: mainTable and classificationTable:
mainTable:
id | classification_id | name
---------------------------------------
1 | 1 | Name1
2 | 2,3,4 | Name2
3 | 1,4 | Name3
4 | 4 | Name4
classificationTable:
classification_id | class_name
---------------------------------------
1 | Class Name1
2 | Class Name2
3 | Class Name3
4 | Class Name4
I want to get a select for example for row with ID 3 from mainTable like:
id = 3
class_name = Class Name1, Class Name4
Name = Name3
I try this select, but this return only first elemnt from array (fore exempla for row with ID 3, this return only Class Name1)
SELECT i.*,
(SELECT GROUP_CONCAT(cl.class_name) FROM classificationTable as cl WHERE cl.classification_id IN(i.classification_id)) as class_name
FROM mainTable as i;
Help PLZ.
Yes, you have a poorly designed database. But you can do what you want.
This requires two steps. The first is to join the mainTable to the classificationTable by looking for each classification_id in the list in the mainTable. You can do this using the
likeoperator.The second step is to bring all the class names back into one column. This is handled using
group_concat.The following query accomplishes this (although it is not tested, so it might have a typo):