简体   繁体   中英

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. Consider a table with 3 columns such as id, col1, col2. Whereas col1 is unique and a update statement contains col1 and col2.

检查这个

We can check if a record exist before a insert statement using select statement. If we follow the same rule during update statement when updating col1 and col2. The statement will stop because record on col1 already exist, even if we update only the 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 .

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. 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 是否唯一的查询中,如果在更新,则添加规则以排除当前更新的项目:

WHERE col1 = 'VALUE' AND id <> X

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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