如果表中已有唯一键,如何强制插入到具有唯一键的表中?
我有一个表:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
替换
:Try
REPLACE
:您还可以使用
INSERT 。 .. ON DUPLICATE KEY UPDATE
语法:请参阅此答案:insert-ignore-vs-insert-on-duplicate-key-update 了解
REPLACE
、INSERT ... ON DUPLICATE KEY UPDATE
和INSERT IGNORE
之间的差异。但请告诉我们
studentId TEXT PRIMARY KEY
是一个拼写错误。你真的有一个主键TEXT
数据类型?名称 (studentId
) 表明它可能是一个简单的INT
或INT AUTO_INCRMENT
。You can also use the
INSERT ... ON DUPLICATE KEY UPDATE
syntax:See this answer: insert-ignore-vs-insert-on-duplicate-key-update for differences between
REPLACE
,INSERT ... ON DUPLICATE KEY UPDATE
andINSERT IGNORE
.But please, tell us that the
studentId TEXT PRIMARY KEY
is a typo. Do you really have a Primary Key that isTEXT
datatype? The name (studentId
) suggests that it could be a simpleINT
orINT AUTO_INCREMENT
.如果您使用的是 MySql - 只需使用 REPLACE 而不是 INSERT
If you are using MySql - just use REPLACE instead of INSERT
我遇到了类似的问题,但是表中已经有数据,并且没有外键,所以我的解决方案非常简单:
我添加了一个名为
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 thetemp_id
column toid
.