如何使用GROUP BY来连接mysql中的字符串 [英] How to use GROUP BY to concat strings in mysql
本文介绍了如何使用GROUP BY来连接mysql中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正常查询
normal query
id sid string
5 1 AAA
6 1 BBB
7 2 CCC
8 3 ZZZ
9 3 EEE
我想 p>
i want
sid string
1 1. AAA 2. BBB
2 1. CCC
3 1. ZZZ 2. EEE
你有任何想法该怎么办?
Do you have any idea how to do?
推荐答案
您可以使用 GROUP_CONCAT()
函数将这些值分成单行,您可以使用用户定义的变量进行赋值 sid
组中的每个值的数字:
You can use the GROUP_CONCAT()
function get the values into a single row and you can use user-defined variables to assign the number to each value in the sid
group:
select sid,
group_concat(concat(rn, '. ', string) ORDER BY id SEPARATOR ' ') string
from
(
select id,
sid,
string,
@row:=case when @prev=sid then @row else 0 end +1 rn,
@prev:=sid
from yourtable
cross join (select @row:= 0, @prev:=null) r
order by id
) src
group by sid
请参阅 SQL Fiddle with Demo ,结果是:
| SID | STRING |
-----------------------
| 1 | 1. AAA 2. BBB |
| 2 | 1. CCC |
| 3 | 1. ZZZ 2. EEE |
这篇关于如何使用GROUP BY来连接mysql中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文