Find out which row fails on adding a constraint in MySQL

删除回忆录丶 提交于 2019-12-24 15:54:51

问题


For this error message, is there a way for mysqlimport to output the specific row that fails the constraint? It's good for debugging. Otherwise, I don't know which row has this problem.

mysqlimport: Error: 1452, Cannot add or update a child row: a foreign key constraint fails (`bwordDS`.`Category_Term`, CONSTRAINT `FK_qn1crq26sr0hqm5q2p7nfvdu1` FOREIGN KEY (`categories_id`) REFERENCES `Category` (`id`)), when using table: Category_Term

回答1:


First check if Category table exist where you are trying to import this data.

if Category table exists then need to check that all category_id in this table should exist in Category table as id.

Better option is to import first category table and then this table.

In generic first all parent tables data should import then child tables.

A dirty way is as per below which is not recommended-

set foreign_key_checks=0;
import data here;
set foreign_key_checks=1;

Just to know which row is creating problem-

Below query will provide you problematic rows.

SELECT a.category_id FROM Category_Term a 
  LEFT JOIN Category b ON a.category_id=b.id 
  WHERE b.id IS NULL;

Note: Assuming category_id in category_term and id in category tables will be indexed.




回答2:


I used the sample query provided by @Zafar, but I added DISTINCT as well:

SELECT DISTINCT contries.city_id 
    FROM contries 
    LEFT JOIN cities ON contries.city_id=city.id 
    WHERE city.id IS NULL;


来源:https://stackoverflow.com/questions/36276053/find-out-which-row-fails-on-adding-a-constraint-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!