Mysql在字段現有內容後面追加內容

  • 2019 年 12 月 5 日
  • 筆記

需求

在發佈系統中所有前置任務裏面增加一些內容,發佈系統中大約有200+的項目,手動是不可能手動的,只有在數據庫中操作了。

思路

思路?既然操作數據庫哪肯定得去看MySQL手冊嘍。

在Mysql手冊中查找String相關資料,找到並進入String Functions,可以找到CONCAT和CONCAT_WS兩個關於字符串拼接的函數文檔鏈接

過程

CONCAT函數

官方解釋:

Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent nonbinary string form. returns NULL if any argument is NULL.

返回結果為連接參數產生的字符串。如有任何一個參數為NULL ,則返回值為 NULL。或許有一個或多個參數。 如果所有參數均為非二進制字符串,則結果為非二進制字符串。 如果自變量中含有任一二進制字符串,則結果為一個二進制字符串。一個數字參數被轉化為與之相等的二進制字符串格式;若要避免這種情況,可使用顯式類型。

函數格式:CONCAT(str1,str2,...)

mysql> select concat('lian','st');  +---------------------+  | concat('lian','st') |  +---------------------+  | lianst              |  +---------------------+  1 row in set (0.00 sec)

CONCAT_WS函數

CONCAT_WS函數與CONCAT函數大致相同,唯一的不同點是CONCAT_WS支持在兩個字符串之間使用分隔符,本次解決問題就是使用的CONCAT_WS函數。

函數格式:CONCAT_WS(separator,str1,str2,...)

CONCAT_WS的第一個參數是分隔符:

  • char(10):換行符
  • char(13):回車符
mysql> select concat_ws(',','lian','st'); # 第一個參數是分隔符  +----------------------------+  | concat_ws(',','lian','st') |  +----------------------------+  | lian,st                    |  +----------------------------+  1 row in set (0.00 sec)    mysql> select concat_ws(char(10),'lian','st');  # 換行符  +---------------------------------+  | concat_ws(char(10),'lian','st') |  +---------------------------------+  | lian  st                         |  +---------------------------------+  1 row in set (0.00 sec)    mysql> select concat_ws(char(13),'lian','st');  # 回車符  +---------------------------------+  | concat_ws(char(13),'lian','st') |  +---------------------------------+  st                         |  +---------------------------------+  1 row in set (0.00 sec)