如何从mySql中的EXECUTE语句插入数据?

时间:2011-04-21 15:36:19

标签: mysql select insert prepared-statement

我在wp_users表中有数据,我想将该表中的数据(ID列除外)复制到另一个名为wp_users2的表中。

如果我不关心我要自动增加的id列,我可以这样做:

insert into wp_users2 (select *, NULL as ID from wp_users)

所以我知道我可以通过键入除ID之外的所有列标题并手动选择那个为NULL来实现此目的,

SELECT NULL as id, col2, col3...

但我想动态地做。我读了this great S.O. post关于如何做到这一点,并且它有效,但是我无法弄清楚如何获取它给我的数据并将其放入插入语句中。

INSERT INTO wp_users2 (
  SET @sql = CONCAT('SELECT NULL as ID,', 
     (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'ID,', '') 
       FROM INFORMATION_SCHEMA.COLUMNS 
       WHERE TABLE_NAME = 'wp_users' 
       AND TABLE_SCHEMA = 'wp1'),
     ' FROM wp_users');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
)

正确的语法是什么?

2 个答案:

答案 0 :(得分:2)

据我所知 - id是AUTO_INCREMENT字段。

因此,尝试使用此脚本作为您的任务的示例 -

CREATE TABLE table1(
  id INT(11) NOT NULL AUTO_INCREMENT,
  column1 VARCHAR(255) DEFAULT NULL,
  column2 VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE table2(
  id INT(11) NOT NULL AUTO_INCREMENT,
  column1 VARCHAR(255) DEFAULT NULL,
  column2 VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (id)
);

INSERT INTO table1 VALUES 
  (1, 'c1', 'c2'),
  (2, 'c3', 'c4');

SET @source_table = 'table1';
SET @target_table = 'table2';
SET @id = 'id';

SET @columns = NULL;
SELECT group_concat(column_name) INTO @columns FROM information_schema.columns
WHERE
  table_schema = 'database_name' -- Set your database name here
  AND table_name = @source_table
  AND column_name != @id;

SET @insert = concat('INSERT INTO ', @target_table, '(', @id, ',', @columns, ') SELECT NULL, ', @columns, ' FROM ', @source_table);
PREPARE stmt1 FROM @insert;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

答案 1 :(得分:2)

set @sql =  (select concat('insert into wp_users2 SELECT NULL,',
             group_concat(column_name),' from ',table_name) from information_schema.columns
         where table_name = 'wp_users' and table_schema = 'wp1' and column_name != 'id'
             order by ordinal_position);

prepare stmt1 from @sql;
execute stmt1;
deallocate prepare stmt1;