mysql judges whether the primary key value exists, if it exists, then update it, if it does not exist, add it

ON DUPLICATE KEY UPDATE can achieve the following purposes:
Insert a record into the database:
If the primary key value / UNIQUE KEY of the data already exists in the table, perform the update operation, that is, the operation after the UPDATE.
Otherwise insert a new record.
Example:

Step1. Create a table and insert test data

SET FOREIGN_KEY_CHECKS=0;


– Table structure for mRowUpdate


DROP TABLE IF EXISTS mRowUpdate;
CREATE TABLE mRowUpdate (
  id int(11) NOT NULL,
  value varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB;


– Records of mRowUpdate


INSERT INTO mRowUpdate VALUES (‘1’, ‘sss’);
INSERT INTO mRowUpdate VALUES (‘2’, ‘szh’);
INSERT INTO mRowUpdate VALUES (‘3’, ‘9999’);
SET FOREIGN_KEY_CHECKS=1;

Step2. Test the use of ON DUPLICATE KEY UPDATE:

INSERT INTO mRowUpdate(id,value) VALUES(3, ‘SuperMan’) ON DUPLICATE KEY UPDATE value=‘SuperMan’;

Guess you like

Origin blog.csdn.net/weixin_42094764/article/details/114658839