MySQL从现有表创建新表

时间:2013-02-01 20:23:19

标签: mysql

我有一个MySQL表Table_A,列出了数字范围及其对应的值:

beg_number
end_number
value

并且需要一个脚本来创建一个新表Table_B,其中包含两个字段,这些字段是所有数字及其对应值的详尽列表:

数 值

beg    end    value

 1      6       11
 7      9       13
 11     14      6
 15     19      3

number value
 1      11
 2      11
 3      11
 4      11
 5      11
 6      11
 7      13
 8      13
 9      13
 11     6
 12     6
 13     6
 14     6
 15     3
 16     3
 17     3
 18     3

这可以通过MySQL脚本完成吗?

1 个答案:

答案 0 :(得分:2)

尝试此商店程序:

CREATE PROCEDURE dorepeat()
BEGIN
  DECLARE xbeg INT;
  DECLARE xend INT;
  DECLARE xvalue INT;
  DECLARE done TINYINT DEFAULT 0;
  DECLARE cur1 CURSOR FOR SELECT beg, end, value FROM TableA;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;
  read_loop: LOOP
    FETCH FROM cur1 INTO xbeg, xend, xvalue;
    IF done THEN LEAVE read_loop; END IF;
    SET @x = xbeg;    

    REPEAT INSERT INTO TableB VALUES (@x, xvalue); SET @x = @x + 1; UNTIL @x > xend END REPEAT;
  END LOOP;
  CLOSE cur1;
END

Here你可以找到我的sqlfiddle;