要复制条目,我想使用以下语法:
insert into TABLE select * from TABLE where ...
但是,由于第一列是自增主键,所以这个值必须不同。我的解决方法是在选择查询中指定所有字段而不是使用星号,然后将主键字段留空。由于我的表有 30 多个字段,不幸的是,这些字段不断变化,我正在寻找一种可以在脚本中实现的解决方案,并且当表结构发生变化时不需要修改。有任何想法吗?非常感谢!
最佳答案
例子:
mysql> create database dbase;
Query OK, 1 row affected (0.00 sec)
mysql> use dbase;
Database changed
mysql> create table tbl ( id integer not null primary key auto_increment, field2 integer, field3 integer );
Query OK, 0 rows affected (0.04 sec)
mysql> SET @sql = CONCAT ( 'SELECT ' , ( SELECT REPLACE ( GROUP_CONCAT( COLUMN_NAME ) , 'id,' , '' ) FROM INFORMATION_SCHEMA.COLUMNS WHERE T
ABLE_NAME = 'tbl' AND TABLE_SCHEMA = 'dbase'), ' FROM tbl');
Query OK, 0 rows affected (0.01 sec)
mysql> select @sql;
+-------------------------------+
| @sql |
+-------------------------------+
| SELECT field2,field3 FROM tbl |
+-------------------------------+
1 row in set (0.00 sec)
mysql>
现在你只需要准备和执行..
mysql> prepare stmt from @sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt;
Empty set (0.00 sec)
没有行返回,因为没有行插入表中。
现在再次插入并执行..
mysql> insert into tbl ( field2, field3 ) values ( 1 , 2 ) , ( 3 , 4 ) ;
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> execute stmt;
+--------+--------+
| field2 | field3 |
+--------+--------+
| 1 | 2 |
| 3 | 4 |
+--------+--------+
2 rows in set (0.00 sec)
返回@sql中指定的除'ID'之外的所有表字段
关于Mysql: SELECT * FROM ....没有一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8590526/