Skip to content
Advertisement

SQL output in one row

For example, I “select * from posts where id = 2”
It will output all of the “id 2” information in 1 row
enter image description here

After normalization, it have a new table for many to many relation.
but I want to know that how can I output the result such as before normalization?
Or I need to modify the output in backend code?

enter image description here

thanks

Advertisement

Answer

One method is group_concat(), which puts all the values in a single row:

select p.*, group_concat(t.name) as tags
from posts p join
     tag_post tp
     on tp.post_id = p.id join
     tag t
     on tp.tag_id = t.id
group by p.id;

Note: This assumes that posts(id) is declared as the primary key (or at least unique) so you can use select p.* with group by.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement