MySQL 多插入? INSERT 失败后 MySQL 数据库完整性

发布于 2024-09-16 06:44:25 字数 72 浏览 6 评论 0原文

是否可以同时向多个表中插入一行?如果你做几个表通过一个ID关联起来;在 INSERT 失败的情况下确保保持完整性的最佳方法是什么?

Is it possible to insert a row into multiple tables at once? If you do several tables related by an ID; what is the best way to ensure integrity is maintained in case an INSERT fails?

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

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

发布评论

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

评论(3

笑红尘 2024-09-23 06:44:25

这正是事务的用途。如果任何命令失败,则自 START TRANSACTION 起的整个事情都会回滚:

START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'foo','bar');
INSERT INTO someothertable VALUES (LAST_INSERT_ID(),'baz');
COMMIT;

这是 MySQL,您不能将事务与 MyISAM 表一起使用(您需要这些表来使用支持某些引擎的引擎)这个,可能是 InnoDB)。

这永远不会被插入到表中(通常您会有一些分支,例如 IF):

START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'data','somemoredata');
ROLLBACK;

警告:更改数据库结构的 SQL 命令结构(例如 CREATE,< code>ALTER,DROP) 无法回滚!

That's exactly what transactions are for. If any of the commands fail, the whole thing since START TRANSACTION is rolled back:

START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'foo','bar');
INSERT INTO someothertable VALUES (LAST_INSERT_ID(),'baz');
COMMIT;

This being MySQL, you can't use transactions with MyISAM tables (you'll need the tables to use some engine that supports this, probably InnoDB).

This will never be inserted into the table (normally you'd have some branching, e.g. an IF):

START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'data','somemoredata');
ROLLBACK;

Caveat: SQL commands which change the database structure (e.g. CREATE,ALTER,DROP) cannot be rolled back!

你是年少的欢喜 2024-09-23 06:44:25

使用交易,卢克。

Use transactions, luke.

停顿的约定 2024-09-23 06:44:25

MySQL 可以插入多行(搜索“多行” )像这样:

INSERT INTO table (field1, field2, ...) VALUES (value1, value2), (value3, value4), etc...

但是,除了查询返回记录、重复项和警告的计数之外,无法判断插入的内容和未插入的内容。您也无法使用 last_insert_id() 来计算新行的 ID,因为它仅返回创建的最后一个 id,而不是一组 id。

如果需要保证完整性,请使用单行插入语句和事务。

MySQL can insert multiple rows (search for 'multiple rows') like this:

INSERT INTO table (field1, field2, ...) VALUES (value1, value2), (value3, value4), etc...

However, there's no way to tell what got inserted and what wasn't due to constraint violations, beyond the query returning a count of records, duplicates, and warnings. You also can't use last_insert_id() to figure out the IDs of the new rows, as that only returns the LAST id that was created, not a set of ids.

If you need to guarantee integrity, then use single row insert statements and transactions.

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