在MySQL数据库中,如果在insert语句后面带上ON DUPLICATE KEY UPDATE 子句,而要插入的行与表中现有记录的惟一索引或主键中产生重复值,那么就会发生旧行的更新;如果插入的行数据与现有表中记录的唯一索引或者主键不重复,则执行新纪录插入操作。
说通俗点就是数据库中存在某个记录时,执行这个语句会更新,而不存在这条记录时,就会插入。
该语句仅mysql可用。
例子Mapper:
<insert id="insertUser" useGeneratedKeys="true" keyProperty="Id"> INSERT INTO user (
username,
password,
role,
userno) VALUES (#{userName}, #{passWord}, #{role}, #{userNo}) ON DUPLICATE KEY UPDATE
username = VALUES(
username),
password = VALUES(
password),
role = VALUES(
role); </insert>
在上述例子中,假设user表有这几个字段,其中userno是唯一键。该sql的效果:插入user信息,如果userNo存在就Update username,password,role;如果userNo不存在就Insert into。
原版sql:insert in to _table(_column1,_column2) values('','') ON DUPLICATE KEY UPDATE _column1 = ''