mysql中函数concat(),concat_ws(),group_concat()的使用方法

1、
CONCAT()函数用于将多个字符串连接成一个字符串
返回结果为连接参数产生的字符串。如有任何一个参数为NULL ,则返回值为 NULL。或许有一个或多个参数。 如果所有参数均为非二进制字符串,则结果为非二进制字符串。 如果自变量中含有任一二进制字符串,则结果为一个二进制字符串。一个数字参数被转化为与之相等的二进制字符串格式;若要避免这种情况,可使用显式类型 cast, 例如: SELECT CONCAT(CAST(int_col AS CHAR), char_col)
mysql> SELECT CONCAT(’My’, ‘S’, ‘QL’);
-> ‘MySQL’
mysql> SELECT CONCAT(’My’, NULL, ‘QL’);
-> NULL
mysql> SELECT CONCAT(14.3);
-> ‘14.3′
mysql中函数concat(),concat_ws(),group_concat()的使用方法


2、
mysql CONCAT_WS(separator,str1,str2,…) 
CONCAT_WS() 代表 CONCAT With Separator ,是CONCAT()的特殊形式。   第一个参数是其它参数的分隔符。分隔符的位置放在要连接的两个字符串之间。分隔符可以是一个字符串,也可以是其它参数。如果分隔符为 NULL,则结果为 NULL。函数会忽略任何分隔符参数后的 NULL 值。
mysql> SELECT CONCAT_WS(’,',’First name’,'Second name’,'Last Name’);
-> ‘First name,Second name,Last Name’
mysql> SELECT CONCAT_WS(’,',’First name’,NULL,’Last Name’);
-> ‘First name,Last Name’
mysql CONCAT_WS()不会忽略任何空字符串。 (然而会忽略所有的 NULL)。
mysql中函数concat(),concat_ws(),group_concat()的使用方法
3、group_concat()

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


select * from goods;  
+------+------+
| id| price|
+------+------+
|1 | 10|
|1 | 20|
|1 | 20|
|2 | 20|
|3 | 200 |
|3 | 500 |
+------+------+
6 rows in set (0.00 sec)

mysql中函数concat(),concat_ws(),group_concat()的使用方法

以id分组,括号中放要连接的字段

+------+--------------------+
| id| group_concat(price) |
+------+--------------------+
|1 | 10,20,20|
|2 | 20 |
|3 | 200,500|
+------+--------------------+
3 rows in set (0.00 sec)



以id分组,把price字段的值在一行打印出来,分号分隔 
select id,group_concat(price separator ';') from goods group by id;  

separator ';'表示用分号分隔
+------+----------------------------------+
| id| group_concat(price separator ';') |
+------+----------------------------------+
|1 | 10;20;20 |
|2 | 20|
|3 | 200;500 |
+------+----------------------------------+
3 rows in set (0.00 sec)


以id分组,把去除重复冗余的price字段的值打印在一行,逗号分隔
select id,group_concat(distinct price) from goods group by id;  

distinct:去除重复冗余的字段的值
+------+-----------------------------+
| id| group_concat(distinct price) |
+------+-----------------------------+
|1 | 10,20|
|2 | 20 |
|3 | 200,500 |
+------+-----------------------------+
3 rows in set (0.00 sec)



以id分组,把price字段的值打印在一行,逗号分隔,按照price倒序排列
select id,group_concat(price order by price desc) from goods group by id;  

order by price desc:倒序排序
+------+---------------------------------------+
| id| group_concat(price order by price desc) |
+------+---------------------------------------+
|1 | 20,20,10 |
|2 | 20|
|3 | 500,200|
+------+---------------------------------------+
3 rows in set (0.00 sec)