美文网首页SQL
[SQL] group_concat

[SQL] group_concat

作者: 何幻 | 来源:发表于2018-08-10 09:25 被阅读21次

1. 背景

在进行查询的时候,
可能在某些情况下,需要对查询到的多条记录进行合并

表a

a1 a2
1  t1
1  t2

我们看到a1字段是相同的,我们期望合并这两条记录为一条,
保持a1不变,a2字段变成t1,t2。即,

a1 merged_a2
1  t1,t2

2. group_concat

在MySQL中使用group_concat以及group by可以实现这个目的,

select
    a1,
    group_concat(a2) as merged_a2
from a
group by a1

查询结果如下,

a1 merged_a2
1  t1,t2

相关文章

网友评论

    本文标题:[SQL] group_concat

    本文链接:https://www.haomeiwen.com/subject/quzhbftx.html