MySQL ON DUPLICATE KEY UPDATE is a unique syntax for Mysql
ON DUPLICATE KEY UPDATE usage and instructions
Usage example:
There is currently a record with id 20 in the database. At this time, the record with insert id = 20 will report an error:
INSERT INTO `book`.`book_test` (`id`, `book_name`, `isbn`, `author`, `price`, `publisher`, `publish_date`, `is_sale`) VALUES ('20', '博弈论', '56', '刘一手', '52.00', '测试出版社', '2018-12-06', '1');
[SQL]INSERT INTO `book`.`book_test` (`id`, `book_name`, `isbn`, `author`, `price`, `publisher`, `publish_date`, `is_sale`) VALUES ('20', '博弈论', '56', '刘一手', '52.00', '测试出版社', '2018-12-06', '1'); [Err] 1062 - Duplicate entry '20' for key 'PRIMARY'
SQL improvements: update if it exists, insert if it doesn't exist
example:
INSERT INTO `book`.`book_test` ( `id`, `book_name`, `isbn`, `author`, `price`, `publisher`, `publish_date`, `is_sale` ) VALUES ( '20', '博弈论', '56', '刘一手', '100.00', '测试出版社', '2018-12-06', '1' ) ON DUPLICATE KEY UPDATE book_name = VALUES (book_name), isbn = VALUES (isbn), author = VALUES (author), price = VALUES (price), publisher = VALUES (publisher), publish_date = VALUES (publish_date), is_sale = VALUES (is_sale)
Results of the:
[SQL]INSERT INTO `book`.`book_test` ( ... VALUES (is_sale) 受影响的行: 2 时间: 0.001s
You can see that the original data has been updated:
Examples of use in Mybatis:
======>> where id and system_id are joint indexes
<insert id="insertOrUpdate" parameterType="com.company.xxx.model.MyTestBean"> insert into ${tableName} <trim prefix="(" suffix=")" suffixOverrides=","> <if test="systemId != null"> system_id, </if> <if test="id != null"> id, </if> <if test="order != null"> order, </if> <if test="desc != null"> desc, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="systemId != null"> #{systemId,jdbcType=INTEGER}, </if> <if test="id != null"> #{id,jdbcType=BIGINT}, </if> <if test="order != null"> #{order,jdbcType=VARCHAR}, </if> <if test="desc != null"> #{desc,jdbcType=LONGVARCHAR}, </if> </trim> ON DUPLICATE KEY UPDATE <trim suffixOverrides=","> <if test="order != null">order=VALUES(order),</if> <if test="desc != null">desc=VALUES(desc),</if> </trim> </insert>