MYSQL命令怎么实现将表中某个字段中多个记录拆分,急求答案!

比如原数据如图,我想将第二个字段中有逗号分隔的多个值分别拆成一行

拆开后成这样的记录

哪位大侠帮帮忙,不胜感激……

觉得你还是应该用php去写。非要用mysql本身的话给个参考:


mysql> select * from a;
+------+--------+------+----+
| id   | name   | num1 | bb |
+------+--------+------+----+
|    1 | a,     |    2 |  3 |
|    2 | b,c,   |    2 |  4 |
|    3 | d,e,f, |    2 |  5 |
+------+--------+------+----+
3 rows in set (0.00 sec)

mysql> delimiter //
mysql> create procedure `strsplit1`(in str3 varchar(2))
    -> begin
    ->  declare i int(10);
    ->  declare j int(10);
    ->  declare k int(10);
    ->  declare str1 varchar(100);
    ->         declare str4 varchar(1000);
    ->  declare str5 varchar(100);
    ->
    ->  select count(*) into i from a;
    ->  if i!=0 then
    ->          drop table if exists tmp_table1;
    ->          CREATE TEMPORARY TABLE tmp_table1 like a;
    ->  end if;
    ->
    ->  set j=0;
    ->  while j<i do
    ->          select id,name into str1,str4 from a limit j,1;
    ->          select instr(str4,str3) into k from dual;
    ->          if k=0 then
    ->                  insert into tmp_table1(id,name) values(str1,str4);
    ->          end if;
    ->          while k!=0 do
    ->                  select substring_index(str4,str3,1) into str5 from dual;
    ->                  insert into tmp_table1(id,name) values(str1,str5);
    ->                  select mid(str4,k+1) into str4 from dual;
    ->                  select instr(str4,str3) into k from dual;
    ->          end while;
    ->  set j=j+1;
    ->  end while;
    ->
    -> select * from tmp_table1;
    -> end
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql>  delimiter ;

最后结果:
mysql> call strsplit1(',');
+------+------+------+----+
| id   | name | num1 | bb |
+------+------+------+----+
|    1 | a    | NULL |  1 |
|    2 | b    | NULL |  2 |
|    2 | c    | NULL |  3 |
|    3 | d    | NULL |  4 |
|    3 | e    | NULL |  5 |
|    3 | f    | NULL |  6 |
+------+------+------+----+
6 rows in set (0.25 sec)

Query OK, 0 rows affected (0.30 sec)

追问

谢谢!php不是很熟,请问能不能帮忙写下代码呢,其中id字段是主键,序号不重复,谢谢了

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-03
如果一定要用Mysql本身的功能,那就只能用存储过程。但我不推荐这么做。因为数据库的主要功能是存储和查询,而比较复杂的计算适合程序去做。存储过程实际上相当于自己定义mysql的函数,这也是有学习成本的。我用了几年mysql,从未用过存储过程。
所以你的问题最好用程序去实现。如果没有特殊的需求,暂时也不需要花费时间学习存储过程的语法。
用程序实现就比较简单,方法不再赘述。本回答被网友采纳
相似回答