我想在 DB 中没有记录的情况下进行 INSERT [英] I want to do INSERT without record in DB

查看:51
本文介绍了我想在 DB 中没有记录的情况下进行 INSERT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将上述问题从非母语英语翻译成英语:

Attempted translation of the above question from non-native English to English:

这是一个关于当值可能已经在数据库中时将值插入数据库时​​使用的最快方法的问题.当值存在时 INSERT 将失败,而当值不存在时 UPDATE 将失败.这些选择中哪一个是最可取的?

This is a question about the fastest method to use when inserting a value into a database when the value may already be in the database. INSERT will fail when the value is there and UPDATE will fail when it is not. Which of these choices is the most desirable?

  • 先执行 SELECT 并选择 INSERT 或 UPDATE.
  • 如果有重复错误,请先插入并使用更新.

如果除了以上还有其他好的选择,请教我.

If there are other good choices besides the above, please teach me.

环境使用 MySQL 4.1.

The environment uses MySQL 4.1.

推荐答案

如果您想在单个语句中执行此操作(听起来像您想要的),我建议使用 INSERT ... ON DUPLICATE KEYUPDATE 语法,如下:

If you want to do this in a single statement (sounds like what you want), I would recommend using the INSERT ... ON DUPLICATE KEY UPDATE syntax, as follows:

INSERT INTO table (id, someothervalue) VALUES (1, 'hi mom')
  ON DUPLICATE KEY UPDATE someothervalue = 'hi mom';

如果不存在具有指定键值(主键或唯一键)的现有记录,则初始 INSERT 语句将执行.如果记录已存在,则执行以下 UPDATE 语句(someothervalue = 3).

The initial INSERT statement will execute if there is no existing record with the specified key value (either primary key or unique). If a record already exists, the following UPDATE statement (someothervalue = 3) is executed.

所有版本的 MySQL 都支持这一点.有关详细信息,请参阅 MySQL 参考手册页面code>INSERT ... ON DUPLICATE KEY UPDATE

This is supported in all versions of MySQL. For more info, see the MySQL Reference Manual page for INSERT ... ON DUPLICATE KEY UPDATE

这篇关于我想在 DB 中没有记录的情况下进行 INSERT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆