我还不太了解 REPLACE INTO 的工作原理。 据我了解,如果任何值与旧行值匹配,它将删除该行并插入更新的数据?
例如我有这张表
+-------------+----------------+------+---------+
| name | value | city | address |
+-------------+----------------+------+---------+
| First book | a value | NY | NULL |
| second book | an other value | LA | NULL |
+-------------+----------------+------+---------+
现在我想改变第二本书的城市并执行
REPLACE INTO book(name,value,city) VALUES ('second book','an other value','CA');
注意:名称和值相同但 mysql 仍插入新行?
+-------------+----------------+------+---------+
| name | value | city | address |
+-------------+----------------+------+---------+
| First book | a value | NY | NULL |
| second book | an other value | LA | NULL |
| second book | an other value | CA | NULL |
+-------------+----------------+------+---------+
最佳答案
正如您可以从 this link 中读到的那样:
The result of the two SQL commands above can be achieved using a single query – using REPLACE INTO. REPLACE statement works the same way as the INSERT query. The only difference is the way they handle duplicate records. If there exists a unique index on a table and you attempted to insert a record that has a key value that’s previously inserted, that record will be deleted first and will insert the new record.
这意味着只有当表中存在一个唯一键时它才会更新,并且您正试图插入一个存在于该键上的值。在那种情况下,更新,否则,进行插入
关于MYSQL替换成永不替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135299/