这些操作应该通过应用程序级别而不是数据库来完成。但是,您真的想从数据库级别执行此操作,您可以使用用户定义的函数轻松执行此操作。这是执行此操作的函数
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 |
+------+-----------------------+
您可以对整个表格执行此操作,也可以在需要时轻松进行更新。