0%

MySQL的concat、concat_ws、group_concat函数

CONCAT()函数

将多个字符串连接成一个字符串。如果有任何一个参数为null,则返回值为null。

举例

1
select concat(id, name, score) as info from tt2;

CONCAT_WS()函数

和concat()一样,将多个字符串连接成一个字符串,不同的是可以指定分隔符。

举例

1
select concat(',', id, name, score) as info from tt2;

GROUP_CONCAT()函数

将group by产生的同一个分组中的值连接起来,返回一个字符串结果。

通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,缺省为一个逗号。

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
select name, group_concat(id) from tt2 group by name;
+-------+------------------+
| name | group_concat(id) |
+-------+------------------+
| jack | 1,2,3 |
| marry | 4,5,6,7,8 |
+-------+------------------+

select name, group_concat(id order by id desc separator '_') from tt2 group by name;
+-------+-------------------------------------------------+
| name | group_concat(id order by id desc separator '_') |
+-------+-------------------------------------------------+
| jack | 3_2_1 |
| marry | 8_7_6_5_4 |
+-------+-------------------------------------------------+

select name, group_concat(concat_ws('-', id, score) order by id desc) from tt2 group by name;
+-------+----------------------------------------------------------+
| name | group_concat(concat_ws('-', id, score) order by id desc) |
+-------+----------------------------------------------------------+
| jack | 3-80,2-75,1-70 |
| marry | 8-82,7-70,6-62,5-85,4-80 |
+-------+----------------------------------------------------------+