首页 > 解决方案 > 一行中的 SQL 输出

问题描述

例如,我“select * from posts where id = 2”
它将在 1 行中输出所有“id 2”信息
在此处输入图像描述

规范化后,它有一个用于多对多关系的新表。
但我想知道如何输出标准化之前的结果?
或者我需要修改后端代码中的输出?

在此处输入图像描述

谢谢

标签: sql

解决方案


一种方法是group_concat(),它将所有值放在一行中:

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;

注意:这假设posts(id)被声明为主键(或至少unique),因此您可以使用select p.*with group by


推荐阅读