官方文档:
- REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.6, “INSERT Statement”.
- REPLACE makes sense only if a table has a PRIMARY KEY or UNIQUE index. Otherwise, it becomes equivalent to INSERT, because there is no index to be used to determine whether a new row duplicates another.
解释:replace
有两个作用:
- 插入的数据在表中没有,将数据插入到表中。
- 插入的数据在表中有:删除表中原有的数据,插入新的数据
注解:以插入两条字段的数据为例,区分是否为相同数据的依据为主键与唯一值。
例如:表中字段为 student_id PRIMARYKEY
id
则若插入的数据中student_id
不同则视为不同数据,反之为相同数据,被覆盖掉。
若想插入两条数据,且两条数据均相同时才视为相同的数据覆盖,反之新插入,则需要将插入的两条数据对应的字段都作为主键唯一标识则可实现。