mysql - 如果它已经在表中,我如何强制 INSERT 插入到具有唯一键的表中?

标签 mysql insert-update upsert

我有一张 table :

CREATE TABLE Students (studentId TEXT PRIMARY KEY, name TEXT);

我想在表中插入记录,如果我插入一个学生两次我想要 第二个插入覆盖(更新)第一条记录。

INSERT INTO Students (StudentId, name) VALUES ('123', 'Jones');
INSERT INTO Students (StudentId, name) VALUES ('123', 'Jonas');

这样做的最佳方法是什么?

最佳答案

尝试 REPLACE :

REPLACE INTO Students (StudentId, name) VALUES ('123', 'Jonas');

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.

关于mysql - 如果它已经在表中,我如何强制 INSERT 插入到具有唯一键的表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8043908/

相关文章:

hibernate - 使用 Hibernate PreInsertEventListener 更改实体

mysql - INSERT ON DUPLICATE KEY 一次更新多行

sql - 具有多列唯一约束名称的 PostgreSQL ON CONFLICT

sql - Upsert 查询不适用于空值。如何在约束中使用空值更新?

mysql - 正确的身份验证 NodeJS Express MySQL

php - 检查用户存在语句是否有效,而电子邮件语句在 PDO 中无效

go - 具有许多属性的 UpdateItem

java - 在 Mongo 中构建倒排列表的更快方法

Python 多处理池在映射调用时挂起

php - 按多个动态条件对 SQL 结果排序