error altering table, adding constraint foreign ke

2020-04-21 04:59发布

mysql> DESCRIBE questions;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(255)     | NO   | PRI | NULL    | auto_increment |
| question | varchar(255) | NO   |     | NULL    |                |
| type     | char(1)      | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE answers;  
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(255)     | NO   | PRI | NULL    | auto_increment |
| answer       | varchar(255) | NO   |     | NULL    |                |
| questionid   | int(255)     | NO   |     | NULL    |                |
| questions_id | int(255)     | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

I am using this statement:

ALTER TABLE answers ADD FOREIGN KEY(questions_id) REFERENCES questions(id); 

but i get this error:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (surveydb.#sql-df_32, CONSTRAINT #sql-df_32_ibfk_1 FOREIGN KEY (questions_id) REFERENCES questions (id))to your MySQL server version for the right syntax to use near 'DESCREBE questions' at line 1

1条回答
闹够了就滚
2楼-- · 2020-04-21 05:52

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
查看更多
登录 后发表回答