更新记录(如果存在);否则插入

发布于 2024-09-24 14:55:23 字数 169 浏览 1 评论 0原文

我想更新表中可能存在或不存在的记录。如果数据库中不存在,则会将其插入。

为了防止选择,我首先使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美男兮 2024-10-01 14:55:23

您可以使用 INSERT ... ON DUPLICATE KEY UPDATE 语法:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

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:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html


The difference between this and REPLACE (Femaref's answer) is that REPLACE will delete the old row and then insert a new row if a key is duplicated, while this will update the existing row.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文