将一个表中的所有行插入到另一个表中 +末尾的时间戳
我正在创建一个与我的活动数据库完全相同的更改日志数据库,只是它末尾有一个更改日期字段。
数据库基本上是一个主键 id,以及大约 50 个其他各种数据类型的列。我在 php 中的脚本是尝试插入新的 id,如果它收到重复主键的错误消息,那么它应该获取该行,将其插入到我的备份数据库中,并使用 curdate() 调用作为最终日期值,从我的第一个数据库中删除该条目,然后插入新条目。
我已经完成了脚本的所有其他部分,除了我必须插入第一个表中的所有内容以及 curdate() 的额外列的部分。或者,如果有更好的解决方案来解决当行数相当多时出现重复主键时插入备份数据库的问题,请分享。
I'm creating a change log db that's the exact same as my active db except it has a changedate DATE field at the end.
The db is basically one primary key id, and about 50 other columns of various data types. The script I have in php is it tries to insert new ids and if it gets the error message for duplicate primary key, then it should get that row, insert it into my backup db with a curdate() call as the final date value, delete the entry from my first db, then insert the new entry.
I have all the other parts of the script finished except the part where I have to insert everything from the first table + an extra column for curdate(). Or if there's a better solution to my problem of inserting into a backup database when a duplicate primary key comes in when there's a fairly high amount of rows please share that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行 INSERT INTO SELECT:
您必须为要复制到备份数据库的条目指定
ID
。您还必须确保ID
不在您的备份表中。您可以使用REPLACE INTO
来解决这种情况。You could do an INSERT INTO SELECT:
You have to specify the
ID
for the entry you wish to copy to your backup db.You have also to be sure, that theID
is not already in your backup table. You can useREPLACE INTO
to workaround this case.基本上,您可以创建一个以
CURRENT_TIMESTAMP
作为默认值的TIMESTAMP
列。当您向该表插入行时,将自动插入当前日期/时间。
这就是您要找的吗?
顺便说一句:我建议从源头解决问题,并确保重复的主键不会插入到数据表中。
为此,您可以使用
SELECT LAST_INSERT_ID();
basicly, you can create a
TIMESTAMP
column withCURRENT_TIMESTAMP
as default value.when you insert a row to that table, the current date/time will be automaticly inserted.
is that what you were looking for ?
BTW: i would recommend to kill the problem at it source and make sure a duplicate primary key will not be inserted to the datatable..
to do that, you can use the
SELECT LAST_INSERT_ID();