"MySQL" unique column Insert duplicate value solution

Source: Internet
Author: User

When inserting records with duplicate values on a unique key, we can control how MySQL handles this situation: using the IGNORE keyword or on DUPLICATE key UPDATE clause skips the INSERT, interrupts the operation, or updates the old record to the new value.

The test is as follows:

If you now insert a record that violates a unique constraint,MySQL interrupts the operation, prompting an error, and when you add the Ignore keyword to the previous INSERT statement, If you think the statement violates the unique constraint, MySQL won't even try to execute this statement, as follows:

When there are many insert statements that need to be executed sequentially, the Ignore keyword makes the operation very convenient. Using it ensures that, regardless of which insert contains duplicate key values, MySQL skips over it (rather than discarding all operations)

In this case, we can also enable MySQL to automatically convert the insert operation to the update operation by adding the on DUPLICATE KEY update clause. This clause must have a list of fields that need to be updated, and this list is the same as the list used by the UPDATE statement.

In this case, if the MySQL discovery table already contains a record with the same unique key, it automatically updates the old record to the new value specified in the DUPLICATE key update clause:

The second approach is recommended for handling unique constraints.

"MySQL" unique column Insert duplicate value solution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.