更新记录(如果存在);否则插入
我想更新表中可能存在或不存在的记录。如果数据库中不存在,则会将其插入。
为了防止选择,我首先使用 UPDATE
语句并检查 affected_rows > 0
如果没有,那么我将此记录插入表中。
我想知道是否有更好的方法来做到这一点?
I want to update a record which may or may not be present in a table. If it is not present in the database then it will be inserted.
To prevent from select I am using UPDATE
statement first and checking affected_rows > 0
if not then I am inserting this record into the table.
I was wondering if there is a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以使用 INSERT ... ON DUPLICATE KEY UPDATE 语法:
http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html
这个和
REPLACE
的区别( Femaref 的答案)是,如果键重复,REPLACE
将删除旧行,然后插入新行,而这将更新现有行。You could use
INSERT ... ON DUPLICATE KEY UPDATE
syntax:http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html
The difference between this and
REPLACE
(Femaref's answer) is thatREPLACE
will delete the old row and then insert a new row if a key is duplicated, while this will update the existing row.