简体   繁体   English

唯一字段的Sql更新语句

[英]Sql update statement for unique field

In MySQL, I've a doubt in sql update query, what is the correct way to check if a certain record exist before update statement.在 MySQL 中,我对 sql update 查询有疑问,在更新语句之前检查某个记录是否存在的正确方法是什么。 Consider a table with 3 columns such as id, col1, col2.考虑一个包含 3 列的表,例如 id、col1、col2。 Whereas col1 is unique and a update statement contains col1 and col2.而 col1 是唯一的,更新语句包含 col1 和 col2。

检查这个

We can check if a record exist before a insert statement using select statement.我们可以使用 select 语句检查插入语句之前是否存在记录。 If we follow the same rule during update statement when updating col1 and col2.如果我们在更新 col1 和 col2 时在 update 语句中遵循相同的规则。 The statement will stop because record on col1 already exist, even if we update only the col2.该语句将停止,因为 col1 上的记录已经存在,即使我们只更新 col2。

If you update (or insert into table), and the new inserted/updated col1 value is already being used on some row, your query should fail with unique constraint violation error .如果您更新(或插入到表中),并且新插入/更新的 col1 值已在某行上使用,则您的查询应该会因唯一约束冲突错误而失败。

Make your application handle this error/exception properly and there's really no need to check the existence of this value before the update/insert.让您的应用程序正确处理此错误/异常,并且确实无需在更新/插入之前检查此值是否存在。 The less queries your application makes the better it is for everyone...您的应用程序的查询越少,对每个人来说就越好......

However, I'd like to draw your attention to the following:但是,我想提请您注意以下几点:
You already seem to have an ID column in your table.您的表中似乎已经有一个 ID 列。 If it's a Primary Key column, then it's definitely unique too.如果它是主键列,那么它也绝对是唯一的。 Now consider, if you really need to have two unique key columns in the table.现在考虑一下,如果您真的需要在表中有两个唯一的键列。 If your application logic is based on the unique values in the col1 column, you can actually drop the ID column and turn col1 into Primary Key instead :)如果您的应用程序逻辑基于 col1 列中的唯一值,您实际上可以删除 ID 列并将 col1 改为主键 :)

在检查 col1 是否唯一的查询中,如果在更新,则添加规则以排除当前更新的项目:

WHERE col1 = 'VALUE' AND id <> X

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM