MySQL 将查询到的一列数据合并成字符串

需求

需要显示人员及其所有的社交账号处于同一行。

表结构如下:
MySQL 将查询到的一列数据合并成字符串_第1张图片

解决方法

使用 group_concat 函数实现。

函数语法:

group_concat( [DISTINCT] 要连接的字段 [Order BY 排序字段 ASC/DESC] [Separator ‘分隔符’] )

SQL语句如下:

select a.`id` 序号, a.`name` 姓名, GROUP_CONCAT(b.`account` separator ';') 账号
from person a, account b
where 1 = 1 
      and a.id = b.person_id
GROUP BY a.id;

查询结果如下:
这里写图片描述

不用group_concat的查询结果为:

select a.`id` 序号, a.`name` 姓名, b.`account` 账号
from person a, account b
where 1 = 1 
      and a.id = b.person_id;

MySQL 将查询到的一列数据合并成字符串_第2张图片


你可能感兴趣的:(MySQL)