MySql可以悄悄放弃外键失败的插入吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了MySql可以悄悄放弃外键失败的插入吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1624字,纯文字阅读大概需要3分钟。
内容图文
![MySql可以悄悄放弃外键失败的插入吗?](/upload/InfoBanner/zyjiaocheng/912/bfe6e050476b4549918d51ce583cce81.jpg)
我正在执行INSERT INTO Foo VALUES(a,b,c,…),有时a,b等中的一个不满足外键约束.
在这种情况下,我希望插入不会发生,并且不会产生错误.
我可以在一个声明中执行此操作,还是必须单独执行IF EXISTS?
解决方法:
是的,使用ignore关键字:
INSERT IGNORE INTO `foo` (...) VALUES (...);
If you use the IGNORE keyword, errors that occur while executing the
INSERT statement are treated as warnings instead. For example, without
IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY
value in the table causes a duplicate-key error and the statement is
aborted. With IGNORE, the row still is not inserted, but no error is
issued.
另一方面,如果您的关注是由于您在父项行之前插入子项,您可以禁用约束并在插入父项后启用它们:
SET FOREIGN_KEY_CHECKS=0;
-- do your inserts not caring about foreign keys
SET FOREIGN_KEY_CHECKS=1;
但这只有在您知道您尊重数据完整性的情况下.
另外,我认为值得在mysql网站上添加关于deferring constraints的评论:
Like MySQL in general, in an SQL statement that inserts, deletes, or
updates many rows, InnoDB checks UNIQUE and FOREIGN KEY constraints
row-by-row. When performing foreign key checks, InnoDB sets shared
row-level locks on child or parent records it has to look at. InnoDB
checks foreign key constraints immediately; the check is not deferred
to transaction commit. According to the SQL standard, the default
behavior should be deferred checking. That is, constraints are only
checked after the entire SQL statement has been processed. Until
InnoDB implements deferred constraint checking, some things will be
impossible, such as deleting a record that refers to itself using a
foreign key.
我们知道MySQL innoDB将来也可以实现这个功能.
内容总结
以上是互联网集市为您收集整理的MySql可以悄悄放弃外键失败的插入吗?全部内容,希望文章能够帮你解决MySql可以悄悄放弃外键失败的插入吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。