MySQL中的字段拼接 concat() concat_ws() group_concat()函數


  • 1.concat()函數
  • 2.concat_ws()函數
  • 3.group_concat()函數 

操作的table

select * from test_concat order by id limit 5;

1.concat()函數

功能:將多個字符串連接成一個字符串。

語法:concat(str1, str2,...),返回結果為連接參數產生的字符串,如果有任何一個參數為null,則返回值為null

3、舉例:

select concat(area,fr,best_history_data) from test_concat order by id limit 5;

如果想在字段間加分隔符,需要在每兩個字段間都增加一個分隔符,比較麻煩:

select concat(area,',',fr,',',best_history_data) as test_result from test_concat order by id limit 5;

2.concat_ws()函數

功能:和concat()一樣,將多個字符串連接成一個字符串,但是可以一次性指定分隔符~(concat_ws就是concat with separator)

語法:concat_ws(separator, str1, str2, ...)

說明:第一個參數指定分隔符。需要注意的是分隔符不能為null,如果為null,則返回結果為null

select concat_ws(',',area,fr,best_history_data) from test_concat order by id limit 5;


注意:和MySQL中concat函數不同的是, concat_ws函數在執行的時候,不會因為NULL值而返回NULL 

mysql> select concat_ws(',','11','22',NULL);
+-------------------------------+
| concat_ws(',','11','22',NULL) |
+-------------------------------+
| 11,22 |
+-------------------------------+
1 row in set (0.00 sec)

3.group_concat()函數

功能:將group by產生的同一個分組中的值連接起來,返回一個字符串結果。

語法:group_concat[distinct要連接的字段 [order by 排序字段 asc/desc  [separator '分隔符')

通過使用distinct可以排除重復值;如果希望對結果中的值進行排序,可以使用order by子句;separator是一個字符串值,缺省為一個逗號。

測試table

select * from test_table;

1.根據area分組,拼接每個區域各個指標的指標值

select group_concat(fr,best_history_data) from test_table group by area;

2.增加分割符

select group_concat(fr,best_history_data separator '|') from test_table group by area;

3.結合concat_ws()函數,在fr與best_history_data之間增加分割符-

select group_concat(concat_ws('-',fr,best_history_data) separator '|') from test_table group by area;

4.根據best_history_data進行排序

select group_concat(concat_ws('-',fr,best_history_data) order by best_history_data desc separator '|') from test_table group by area;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM