如果表中已有唯一键,如何强制插入到具有唯一键的表中?

发布于 2024-12-13 22:59:20 字数 329 浏览 2 评论 0原文

我有一个表:

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');

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

I have a table:

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

I want to insert records into the table, if I insert a student twice I want
the second insert to override(update) the first record.

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

What's the best way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

舂唻埖巳落 2024-12-20 22:59:20

尝试替换

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

REPLACE 的工作方式与 INSERT 完全相同,只不过如果表中的旧行与 PRIMARY KEY 或 UNIQUE 索引的新行具有相同的值,则在插入新行之前会删除旧行。

Try 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.

ぶ宁プ宁ぶ 2024-12-20 22:59:20

您还可以使用 INSERT 。 .. ON DUPLICATE KEY UPDATE 语法:

INSERT INTO Students
    (StudentId, name) 
  VALUES ('123', 'Jones')
ON DUPLICATE KEY UPDATE
  name = VALUES(name) ;

请参阅此答案:insert-ignore-vs-insert-on-duplicate-key-update 了解 REPLACEINSERT ... ON DUPLICATE KEY UPDATEINSERT IGNORE 之间的差异。


但请告诉我们 studentId TEXT PRIMARY KEY 是一个拼写错误。你真的有一个主键 TEXT 数据类型?名称 (studentId) 表明它可能是一个简单的 INTINT AUTO_INCRMENT

You can also use the INSERT ... ON DUPLICATE KEY UPDATE syntax:

INSERT INTO Students
    (StudentId, name) 
  VALUES ('123', 'Jones')
ON DUPLICATE KEY UPDATE
  name = VALUES(name) ;

See this answer: insert-ignore-vs-insert-on-duplicate-key-update for differences between REPLACE, INSERT ... ON DUPLICATE KEY UPDATE and INSERT IGNORE.


But please, tell us that the studentId TEXT PRIMARY KEY is a typo. Do you really have a Primary Key that is TEXT datatype? The name (studentId) suggests that it could be a simple INT or INT AUTO_INCREMENT.

↘紸啶 2024-12-20 22:59:20

如果您使用的是 MySql - 只需使用 REPLACE 而不是 INSERT

If you are using MySql - just use REPLACE instead of INSERT

梨涡少年 2024-12-20 22:59:20

我遇到了类似的问题,但是表中已经有数据,并且没有外键,所以我的解决方案非常简单:
我添加了一个名为 temp_id 的新列,并将其设为主键,然后删除了旧的 ID 列,然后将 temp_id 列重命名为 id

I had a similar issue, but with a table that already had data in it, and no foreign keys, so my solution was very simple:
I added a new column called temp_id and made that a primary key, then afterwards deleted the old ID column, and then renamed the temp_id column to id.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文