问题
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_1FOREIGN KEY (questions_id) REFERENCESquestions(id))to your MySQL server version for the right syntax to use near 'DESCREBE questions' at line 1
回答1:
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
来源:https://stackoverflow.com/questions/20871433/error-altering-table-adding-constraint-foreign-key-getting-error-cannot-add-or