SQLite“插入或替换”与“更新...何处”

发布于 2024-08-21 20:54:08 字数 207 浏览 2 评论 0原文

我以前从未见过 SQL 中使用的语法 INSERT OR REPLACE INTO names (id, name) VALUES (1, "John"),我想知道为什么它比 UPDATE names 更好SET name = "John" WHERE id = 1。有什么充分的理由使用其中一种而不是另一种吗?这个语法是 SQLite 特有的吗?

I've never seen the syntax INSERT OR REPLACE INTO names (id, name) VALUES (1, "John") used in SQL before, and I was wondering why it's better than UPDATE names SET name = "John" WHERE id = 1. Is there any good reason to use one over the other. Is this syntax specific to SQLite?

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

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

发布评论

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

评论(4

套路撩心 2024-08-28 20:54:08

如果该行不存在,则 UPDATE 将不会执行任何操作。

如果该行不存在,则 INSERT OR REPLACE 将插入,如果存在则替换值。

UPDATE will not do anything if the row does not exist.

Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.

吾家有女初长成 2024-08-28 20:54:08

另一个需要注意的事实是:INSERT OR REPLACE 将替换语句中未提供的任何值。

例如,如果您的表包含您没有提供值的“姓氏”列,则 INSERT OR REPLACE 将在可能的情况下使“姓氏”无效(如果约束允许),否则会失败。

Another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement.

For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (if constraints allow it), or fail.

—━☆沉默づ 2024-08-28 20:54:08
REPLACE INTO table(column_list) VALUES(value_list);

INSERT OR REPLACE INTO table(column_list) VALUES(value_list);

为了使 REPLACE 正确执行,您的表结构必须具有唯一的行,无论是简单的主键还是唯一的索引

REPLACE 删除记录,然后插入记录,如果您设置了它们,则会导致执行 INSERT 触发器。如果您在 INSERT 上有触发器,则可能会遇到问题。


这是一个解决方法..未检查速度..

INSERT OR IGNORE INTO table (column_list) VALUES(value_list);

随后

UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'

此方法允许在不引起触发的情况下进行替换。

REPLACE INTO table(column_list) VALUES(value_list);

is a shorter form of

INSERT OR REPLACE INTO table(column_list) VALUES(value_list);

For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.

REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.


This is a work around.. not checked the speed..

INSERT OR IGNORE INTO table (column_list) VALUES(value_list);

followed by

UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'

This method allows a replace to occur without causing a trigger.

惜醉颜 2024-08-28 20:54:08

如果 id=1 尚不存在,插入或替换查询将插入一条新记录。

如果id=1已经存在,更新查询只会更新它,如果它不存在,它不会创建新记录。

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

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