Create test---book chart of subjects
CREATE TABLE `book` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_code` varchar(30) NOT NULL,
`book_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_code` (`unique_code`) USING BTREE COMMENT 'book unique_code'
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
The premise is that there is an index in the table: the following unique_code is the index
Requirements: Need to import data to book table. When the data of the account exists in the book table, update the data value, otherwise insert inserts a new record.
Previous practice: loop whether the book record in the select table exists, use update if it exists, or use insert if it does not exist.
Disadvantages of the practice: every time a record is processed, the database needs to be operated twice (select, update/insert)
Optimization method: use insert statement with on duplicate key update.
Practice Note: For example, the above requirements need to use the unique unique_code index of the book table
1. Execute the following command
insert into book(
unique_code,
book_name
) values (
'zs-001',
'中文'
) on duplicate key update book_name='数学';
2. Execute the step 1 command again and you will find that the value of book_name has changed