5-05 2,908 views
Mysql的查询结果行字段拼接,可以用下面两个函数实现:
"1.concat函数"
mysql> select concat('1','2','3') from test ;
+---------------------+
| concat('1','2','3') |
+---------------------+
| 123 |
+---------------------+
如果连接串中存在NULL,则返回结果为NULL:
mysql> select concat('1','2',NULL,'3') from test ;
+--------------------------+
| concat('1','2',NULL,'3') |
+--------------------------+
| NULL |
+--------------------------+
"2.concat_ws函数"
mysql> select concat_ws(':','1','2','3') from test ;
+----------------------------+
| concat_ws(':','1','2','3') |
+----------------------------+
| 1:2:3 |
+-------------------
分隔符为NULL,则返回结果为NULL:
mysql> select concat_ws(NULL,'1','2','3') from test;
+-----------------------------+
| concat_ws(NULL,'1','2','3') |
+-----------------------------+
| NULL |
+-----------------------------+
如果参数中存在NULL,则会被忽略:
mysql> select concat_ws(':','1','2',NULL,NULL,NULL,'3') from test ;
+-------------------------------------------+
| concat_ws(':','1','2',NULL,NULL,NULL,'3') |
+-------------------------------------------+
| 1:2:3 |
+-------------------------------------------+
可以对NULL进行判断,并用其它值进行替换:
mysql> select concat_ws(':','1','2',ifNULL(NULL,'0'),'3') from bank limit 1;
+---------------------------------------------+
| concat_ws(':','1','2',ifNULL(NULL,'0'),'3') |
+---------------------------------------------+
| 1:2:0:3 |
+---------------------------------------------+