ON DUPLICATE KEY UPDATE用法与说明
ON DUPLICATE KEY UPDATE是mysql中特有语法.切勿在别的数据库中使用
用法主要是靠唯一约束来实现新增操作转变成修改操作
先上代码
- mybatis中使用
INSERT INTO test(
id, code, `name`, `status`, gmt_create, gmt_modified
)
VALUES
<foreach collection="list" index="index" item="item" open="(" separator="),(" close=")">
#{item.id}, #{item.code}, #{item.name}, #{item.status}, now(), now()
</foreach>
ON DUPLICATE KEY UPDATE
status= values(status),
gmt_modified = values(gmt_modified)
- sql中使用
INSERT INTO test(id, code, `name`, `status`, gmt_create, gmt_modified) VALUES (1,"CODE","哈哈先生","静止状态",now(), now())
ON DUPLICATE KEY UPDATE
status= values(status),
gmt_modified = values(gmt_modified)
如代码所示.
id为主键
当表中已有一条id=1的数据时.
此时我执行上面的sql,依然会执行成功.
因为在新增的过程中,因为id=1已存在,有唯一约束,所以ON DUPLICATE KEY UPDATE就把新增操作转变为了对id=1的修改操作
status= values(status),
gmt_modified = values(gmt_modified)
这两条是告诉mysql.修改操作要修改的字段.
最后的执行结果就是,id=1的数据.
status修改成了"静止状态",gmt_modified修改成了当前时间