INSERT INTO...SELECT 对于所有 MySQL 列
我正在尝试移动旧数据:
this_table >> this_table_archive
复制所有列。我已经尝试过这个,但它不起作用:
INSERT INTO this_table_archive (*) VALUES (SELECT * FROM this_table WHERE entry_date < '2011-01-01 00:00:00');
注意:这些表是相同的,并且将 id
设置为主键。
I'm trying to move old data from:
this_table >> this_table_archive
copying all columns over. I've tried this, but it doesn't work:
INSERT INTO this_table_archive (*) VALUES (SELECT * FROM this_table WHERE entry_date < '2011-01-01 00:00:00');
Note: the tables are identical and have id
set as a primary key.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除了 Mark Byers 的回答:
有时您还想插入硬编码详细信息,否则可能会出现唯一约束失败等情况。因此,在覆盖某些列值的情况下,请使用以下内容。
这里 domain 值是我以硬编码方式添加的,以摆脱唯一约束。
Addition to Mark Byers answer :
Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.
Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.
你不需要 double () 作为值位吗?如果不尝试这个(尽管一定有更好的方法
don't you need double () for the values bit? if not try this (although there must be a better way
手册中描述了正确的语法。试试这个:
如果 id 列是自动增量列,并且您在两个表中都已经有一些数据,那么在某些情况下您可能希望从列列表中省略 id 并生成新的 id 以避免插入已经存在的 id在原来的表中。如果您的目标表为空,那么这不会成为问题。
The correct syntax is described in the manual. Try this:
If the id columns is an auto-increment column and you already have some data in both tables then in some cases you may want to omit the id from the column list and generate new ids instead to avoid insert an id that already exists in the original table. If your target table is empty then this won't be an issue.
对于语法,它看起来像这样(省略列列表以隐式表示“全部”)
如果归档表中已有数据,则避免主键错误
For the syntax, it looks like this (leave out the column list to implicitly mean "all")
For avoiding primary key errors if you already have data in the archive table