简体   繁体   English

识别多行插入的值失败外键约束

[英]Identifying which value of a multi-row inserts fails foreign key constraint

I have a multi-row insert that looks something like: 我有一个多行插入,看起来像:

insert into table VALUES
(1, 2, 3),
(4, 5, 6),
(7, 8, 9);

Assume the first attribute (1, 4, 7) is a foreign key to another table and assume that this referenced table does not have the value '4'. 假定第一个属性(1、4、7)是另一个表的外键,并假定此引用表的值不为'4'。 A MySQLExeption is thrown with error code 1452. 抛出MySQLExeption,错误代码为1452。

EXCEPTION: Cannot add or update a child row: a foreign key constraint fails ( dbName/tableName , CONSTRAINT id FOREIGN KEY ( customer_id ) REFERENCES referencedTable ( customer_id )) 例外:无法添加或更新子行:外键约束失败( dbName/tableName ,CONSTRAINT id FOREIGN KEY( customer_id )参考referencedTablecustomer_id ))

Is there a way to identify which value caused the error? 有没有办法确定哪个值导致了错误? I would love to give my user an error message that said something like: 我想给我的用户一条错误消息,内容如下:

Error: '4' does not exist in the referenced table. 

I am using the .NET mysql connector to execute the insert. 我正在使用.NET mysql连接器来执行插入。

Thanks- 谢谢-

Jonathan 乔纳森

One option could be to query the referenced table first. 一种选择是首先查询引用的表。

select id from referencedTable where id not in (1, 4, 7)

It seems that there should be a cleaner way... 似乎应该有一种更清洁的方式...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM