Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

前端 未结 21 2323
生来不讨喜
生来不讨喜 2020-11-22 01:32

I\'m having a bit of a strange problem. I\'m trying to add a foreign key to one table that references another, but it is failing for some reason. With my limited knowledge o

21条回答
  •  长发绾君心
    2020-11-22 02:36

    Use NOT IN to find where constraints are constraining:

    SELECT column FROM table WHERE column NOT IN 
    (SELECT intended_foreign_key FROM another_table)
    

    so, more specifically:

    SELECT sourcecode_id FROM sourcecodes_tags WHERE sourcecode_id NOT IN 
    (SELECT id FROM sourcecodes)
    

    EDIT: IN and NOT IN operators are known to be much faster than the JOIN operators, as well as much easier to construct, and repeat.

提交回复
热议问题