INSERT ... ON DUPLICATE KEY UPDATE is a statement in MySQL that performs insertion or update operations when repeated key conflicts are handled. Its core mechanism is: if the insertion data does not violate the primary key or unique constraint, it will be inserted normally; if it conflicts, the update part will be executed. This statement is suitable for user registration, order writing and other scenarios, and can simplify logic and ensure data integrity. Key points of use include: 1. The table must define a primary key or a unique index; 2. The update of multiple fields must be separated by commas; 3. The insertion value can be referenced through the VALUES() function; 4. It supports inserting multiple rows at a time, and each row independently determines whether it is updated. Notes include: Ensure the index is accurate to avoid misinterpretation, pay attention to lock performance under high concurrency, use transaction control reasonably, and be sure to test and verify before going online.
MySQL's INSERT ... ON DUPLICATE KEY UPDATE
is a very practical function, especially when processing duplicate data, which can avoid errors and automatically update existing records. Its core function is: if the inserted data does not conflict with unique constraints or primary key constraints, it will be inserted normally; if it conflicts, the subsequent update operation will be automatically performed .

This is used a lot in actual development, such as user registration, order writing, data statistics and other scenarios, which can not only ensure data integrity, but also simplify logical judgments.
What is "Duplicate Key"?
The prerequisite for understanding this statement is to understand what a "repeat key" is.

The primary key (PRIMARY KEY) and unique index (UNIQUE INDEX) in MySQL can be used as criteria for determining whether it is duplicated. When you insert a record, if a field value already exists in these constraint fields, a "duplicate key error" is triggered.
And ON DUPLICATE KEY UPDATE
will not report an error in this case, but will execute the update part you specified.

For example:
CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR(100) UNIQUE, name VARCHAR(50), age INT );
In this table, email
is unique. If you execute:
INSERT INTO users (email, name, age) VALUES ('test@example.com', 'Tom', 25) ON DUPLICATE KEY UPDATE name = 'Jerry', age = 30;
- If
'test@example.com'
does not exist yet, a new record will be inserted; - If it already exists, the corresponding record
name
will be changed to'Jerry'
andage
will be changed to30
.
Several key points in actual use
1. Ensure there is a corresponding unique constraint or primary key
This is the most basic point. If UNIQUE
or PRIMARY KEY
is not defined, then ON DUPLICATE KEY UPDATE
will not take effect and will not have any effect.
Common errors:
- Forgot to add a unique index to the field
- Insert multiple fields into a unique combination, but only a single field index is added
Therefore, when designing the table structure, you must figure out which fields need unique constraints and add them in advance.
2. When updating multiple fields, the syntax must be correct
When updating multiple fields, you need to separate them with commas:
INSERT INTO users (email, name, age) VALUES ('test@example.com', 'Tom', 25) ON DUPLICATE KEY UPDATE name = 'Jerry', age = 30;
Do not miss commas or write the wrong field name.
3. It can be used in conjunction with the VALUES() function
If you want to reference the inserted value when updating, you can use VALUES(column_name)
:
INSERT INTO users (email, name, age) VALUES ('test@example.com', 'Tom', 28) ON DUPLICATE KEY UPDATE name = VALUES(name), age = VALUES(age) 1;
What this means here:
- If there is a conflict, set
name
to the value passed when inserting; - Set
age
to the insert value plus 1.
This is useful for some statistics class operations, such as updating the counter every time you insert it.
4. Multiple inserts can also be processed together
You can insert multiple lines at once, each line will trigger a check:
INSERT INTO users (email, name, age) VALUES ('a@example.com', 'A', 10), ('b@example.com', 'B', 20) ON DUPLICATE KEY UPDATE name = VALUES(name), age = VALUES(age);
If there is a conflict in one line, only that line will be updated and the other lines will be inserted as usual.
Recommendations and precautions for use
- Avoid mis-update : Make sure that the unique index is accurate, otherwise it may be updated to records that should not be updated.
- Performance considerations : Frequent use of this statement has little impact on performance, but if the concurrency is very high, you should pay attention to the locking problem.
- Transaction control : If used in a transaction, ensure logical consistency.
- Test verification : Be sure to test before going online, especially when joint unique indexes are in the case of errors.
In general, INSERT ... ON DUPLICATE KEY UPDATE
is a very easy to use and safe operation, suitable for most scenarios that require "insert or update". As long as the table structure is designed reasonably, it is very easy to use.
Basically all of this is it. You need to pay more attention to the details that are not complicated but are prone to ignore.
The above is the detailed content of mysql insert on duplicate key update. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The default user name of MySQL is usually 'root', but the password varies according to the installation environment; in some Linux distributions, the root account may be authenticated by auth_socket plug-in and cannot log in with the password; when installing tools such as XAMPP or WAMP under Windows, root users usually have no password or use common passwords such as root, mysql, etc.; if you forget the password, you can reset it by stopping the MySQL service, starting in --skip-grant-tables mode, updating the mysql.user table to set a new password and restarting the service; note that the MySQL8.0 version requires additional authentication plug-ins.

GTID (Global Transaction Identifier) ??solves the complexity of replication and failover in MySQL databases by assigning a unique identity to each transaction. 1. It simplifies replication management, automatically handles log files and locations, allowing slave servers to request transactions based on the last executed GTID. 2. Ensure consistency across servers, ensure that each transaction is applied only once on each server, and avoid data inconsistency. 3. Improve troubleshooting efficiency. GTID includes server UUID and serial number, which is convenient for tracking transaction flow and accurately locate problems. These three core advantages make MySQL replication more robust and easy to manage, significantly improving system reliability and data integrity.

There are three ways to modify or reset MySQLroot user password: 1. Use the ALTERUSER command to modify existing passwords, and execute the corresponding statement after logging in; 2. If you forget your password, you need to stop the service and start it in --skip-grant-tables mode before modifying; 3. The mysqladmin command can be used to modify it directly by modifying it. Each method is suitable for different scenarios and the operation sequence must not be messed up. After the modification is completed, verification must be made and permission protection must be paid attention to.

MySQL main library failover mainly includes four steps. 1. Fault detection: Regularly check the main library process, connection status and simple query to determine whether it is downtime, set up a retry mechanism to avoid misjudgment, and can use tools such as MHA, Orchestrator or Keepalived to assist in detection; 2. Select the new main library: select the most suitable slave library to replace it according to the data synchronization progress (Seconds_Behind_Master), binlog data integrity, network delay and load conditions, and perform data compensation or manual intervention if necessary; 3. Switch topology: Point other slave libraries to the new master library, execute RESETMASTER or enable GTID, update the VIP, DNS or proxy configuration to

The steps to connect to the MySQL database are as follows: 1. Use the basic command format mysql-u username-p-h host address to connect, enter the username and password to log in; 2. If you need to directly enter the specified database, you can add the database name after the command, such as mysql-uroot-pmyproject; 3. If the port is not the default 3306, you need to add the -P parameter to specify the port number, such as mysql-uroot-p-h192.168.1.100-P3307; In addition, if you encounter a password error, you can re-enter it. If the connection fails, check the network, firewall or permission settings. If the client is missing, you can install mysql-client on Linux through the package manager. Master these commands

InnoDB implements repeatable reads through MVCC and gap lock. MVCC realizes consistent reading through snapshots, and the transaction query results remain unchanged after multiple transactions; gap lock prevents other transactions from inserting data and avoids phantom reading. For example, transaction A first query gets a value of 100, transaction B is modified to 200 and submitted, A is still 100 in query again; and when performing scope query, gap lock prevents other transactions from inserting records. In addition, non-unique index scans may add gap locks by default, and primary key or unique index equivalent queries may not be added, and gap locks can be cancelled by reducing isolation levels or explicit lock control.

Toalteralargeproductiontablewithoutlonglocks,useonlineDDLtechniques.1)IdentifyifyourALTERoperationisfast(e.g.,adding/droppingcolumns,modifyingNULL/NOTNULL)orslow(e.g.,changingdatatypes,reorderingcolumns,addingindexesonlargedata).2)Usedatabase-specifi

IndexesinMySQLimprovequeryspeedbyenablingfasterdataretrieval.1.Theyreducedatascanned,allowingMySQLtoquicklylocaterelevantrowsinWHEREorORDERBYclauses,especiallyimportantforlargeorfrequentlyqueriedtables.2.Theyspeedupjoinsandsorting,makingJOINoperation
