El uso de la sintaxis ON DUPLICATE KEY UPDATE en MySQL

MySQL ON DUPLICATE KEY UPDATE es una sintaxis única para Mysql

ON DUPLICATE KEY UPDATE uso e instrucciones 

Práctica de INSERT ... ON DUPLICATE KEY UPDATE en Mysql

INSERTAR ... EN LA ACTUALIZACIÓN DE CLAVE DUPLICADA 语句

Ejemplo de uso:

Actualmente hay un registro con id 20 en la base de datos. En este momento, el registro con id de inserción = 20 reportará un 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'

Mejoras de SQL: actualizar si existe, insertar si no existe

ejemplo:

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)

Resultados del: 

[SQL]INSERT INTO `book`.`book_test` (
...
VALUES
	(is_sale)
受影响的行: 2
时间: 0.001s

Puede ver que los datos originales se han actualizado: 

Ejemplos de uso en Mybatis:

====== >> donde id y system_id son índices conjuntos

<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>

 

Supongo que te gusta

Origin blog.csdn.net/xiangwang2016/article/details/106527878
Recomendado
Clasificación