Skip to content
Advertisement

How to list data from join table in one row?

There 3 entities: 1) Question, 2) Tag and join table between them – question_has_tag.

When I make a select query like:

select * from question_has_tag as qht where qht.question_id = 6;

I’m getting the following result:

question_id| tag_id
6          | 1
6          | 2
6          | 3

and I needed to get:

question_id| tag_id
6          | 1, 2, 3

How to get it ?

Advertisement

Answer

You need to GROUP them and use GROUP_CONCAT

Like

SELECT question_id,GROUP_CONCAT(tag_id ORDER BY tag_id )
FROM question_has_tag as qht 
WHERE qht.question_id = 6
GROUP BY question_id;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement