【问题标题】:How to detect the row which caused foreign key constraint violation?如何检测导致违反外键约束的行?
【发布时间】:2020-11-20 23:31:17
【问题描述】:

对于表table1_table2_map这样的语句

INSERT INTO table1_table2_map 
(table1_id, table2_id) 
VALUES 
(-999,-999), -- Both Valid
(3,4), -- Both Bad
(-999, 3) -- One is Bad

上面提到的表有两个外键引用:

 `FOREIGN KEY (`table1_id`) REFERENCES `table1_lkp` 
 ` FOREIGN KEY (`table2_id`) REFERENCES `table2_lkp` 

插入错误如下:

> Cannot add or update a child row: a foreign key constraint fails (`test_nv2rnuw4yh`.`table1_table2_map`, CONSTRAINT `fk_table1_id` FOREIGN KEY (`table1_id`) REFERENCES `table1_lkp` (`table1_id`)).

如何检测一行引发错误的信息?

【问题讨论】:

标签: mysql


【解决方案1】:

如果您有 MySQL 8.0.19 或更高版本,您可以使用 row 将您的 values 转换为这样的选择查询,例如:

select col1, col2
from (
    VALUES 
        row(-999,-999)
     ,  row(3,4),
     ,  row(-999, 3)  
      ) d (col1, col2)
where not exists (select null from table1_lkp where d.col1 = table1_lkp.table1_id)
or not exists (select null from table2_lkp where d.col2 = table2_lkp.table2_id)

如果您不能使用row,则在使用 union all 的查询中转换值以形成所需的行

select col1, col2
from (
    select -999 as col1 ,-999 as col2 union all
    select 3,4 union all
    select -999, 3 union all 
      ) d
where not exists (select null from table1_lkp where d.col1 = table1_lkp.table1_id)
or not exists (select null from table2_lkp where d.col2 = table2_lkp.table2_id)

【讨论】:

  • 不幸的是,我使用的是 Mysql 5.6。那有关系吗?我会尝试你的建议并回复
  • 对于旧版本的 MySQL,您需要使用第二种方法,因为在 MySQL 8.0.19 中引入了row,请参阅dev.mysql.com/doc/refman/8.0/en/values.html
猜你喜欢
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多