error altering table, adding constraint foreign key getting error “Cannot add or update a child row”

后端 未结 1 1675
南旧
南旧 2021-01-26 23:02
mysql> DESCRIBE questions;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+--         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-26 23:39

    You have at least one data value in answers.questions_id that does not occur in questions.id.

    Here's an example of what I mean:

    mysql> create table a ( id int primary key);
    
    mysql> create table b ( aid int );
    
    mysql> insert into a values (123);
    
    mysql> insert into b values (123), (456);
    
    mysql> alter table b add foreign key (aid) references a(id);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint 
    fails (`test`.`#sql-3dab_e5c`, CONSTRAINT `#sql-3dab_e5c_ibfk_1` FOREIGN KEY
    (`aid`) REFERENCES `a` (`id`))
    

    You can use this to confirm that there are unmatched values:

    SELECT COUNT(*)
    FROM answers AS a
    LEFT OUTER JOIN questions AS q ON a.questions_id = q.id
    WHERE q.id IS NULL
    

    0 讨论(0)
提交回复
热议问题