MYSQL替换成永不替换?

标签 mysql sql

我还不太了解 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/

相关文章:

mysql - 如何获取特定 event_id 的最后 revision_id?

sql - SQL Server中的转换错误-为什么?

java - 使用 Hibernate 时如何打印带有参数值的查询字符串

java - 在 Android Studio 中将数据从 MySQL 显示到 TextView

sql - Oracle:在 PostgreSQL 中有与 ROW 等价的东西吗?

mysql - 如何对多行求和?

mysql - MyISAM:如何在运行 DELETE 的情况下进行 SELECT 而无需锁定等待?

php - 为什么准备好的语句中的计算 'like' 子句需要括号?

MySql - 如何获取最后一个 ALTER TABLE 的日期时间?

mysql - 将 'time' 列更改为 'datetime'