這些操作應該通過應用程序級而不是數據庫來完成。但是,您真的想從數據庫級別執行此操作,您可以使用用戶定義的函數輕鬆完成此操作。下面是一個函數來做到這一點
delimiter //
create function myFunction(myString varchar(255))
returns varchar(255)
begin
declare strLen int ;
declare lookupChar char(1);
declare finalString varchar(255);
declare x int;
set strLen = length(myString);
set x = 1 ;
set finalString = '';
while x <= strLen do
set lookupChar = substring(myString,x,1);
if finalString = '' then
set finalString = lookupChar;
else
set finalString = concat(finalString,',',lookupChar);
end if;
set x = x+1;
end while;
return finalString;
end//
delimiter;
讓我們在MySQL
mysql> create table mytable (id int, value varchar(100));
Query OK, 0 rows affected (0.19 sec)
mysql> insert into mytable values (1,'AHGJTOSIYGJ'),(2,'OTPDBSKGY'),(3,'HFRYEC'),(4,'OPFKWIFS');
Query OK, 4 rows affected (0.02 sec)
mysql> select * from mytable ;
+------+-------------+
| id | value |
+------+-------------+
| 1 | AHGJTOSIYGJ |
| 2 | OTPDBSKGY |
| 3 | HFRYEC |
| 4 | OPFKWIFS |
+------+-------------+
4 rows in set (0.00 sec)
運行此現在,讓我們創建函數
mysql> delimiter //
mysql> create function myFunction(myString varchar(255))
-> returns varchar(255)
-> begin
-> declare strLen int ;
-> declare lookupChar char(1);
-> declare finalString varchar(255);
-> declare x int;
->
-> set strLen = length(myString);
-> set x = 1 ;
-> set finalString = '';
-> while x <= strLen do
-> set lookupChar = substring(myString,x,1);
-> if finalString = '' then
-> set finalString = lookupChar;
-> else
-> set finalString = concat(finalString,',',lookupChar);
-> end if;
-> set x = x+1;
-> end while;
-> return finalString;
-> end//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
到目前爲止好,現在讓我們選擇使用的值功能
mysql> select id,myFunction(value) as value from mytable ;
+------+-----------------------+
| id | value |
+------+-----------------------+
| 1 | A,H,G,J,T,O,S,I,Y,G,J |
| 2 | O,T,P,D,B,S,K,G,Y |
| 3 | H,F,R,Y,E,C |
| 4 | O,P,F,K,W,I,F,S |
+------+-----------------------+
Y ou可以爲整個表執行此操作,並且如果需要,還可以輕鬆完成更新。
可能重複[如何在MySQL中執行正則表達式替換?](http://stackoverflow.com/questions/986826/how-to-do-a-regular-expression-replace-in-mysql) – Jens