如果您不想列出所有字段,则必须使用 information_schema 和prepared statements。
这是一个例子
set @str = (select concat('insert into ', table_name,' (', group_concat(column_name),')',' select ',group_concat(column_name),' from ', table_name, ' where id = 1') from
information_schema.columns
where table_schema = 'your_db' and table_name = 'your_table'
and column_key <> 'PRI');
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;
您甚至可以在存储过程中通过以下方式对其进行转换:向其传递三个参数(id、表名和数据库名):
delimiter //
drop procedure if exists copy_record //
create procedure copy_record(in my_id int, in my_db varchar(50), in my_table varchar(50) )
begin
set @str = (select concat('insert into ', table_name,' (', group_concat(column_name),')',' select ',group_concat(column_name),' from ', table_name, ' where id = ',my_id) from
information_schema.columns
where table_schema = my_db and table_name = my_table
and column_key <> 'PRI');
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;
end; //
delimiter ;
call copy_record(1,'db_name','table_name');