/ / errore alterando la tabella, aggiungendo la chiave esterna di restrizione ottenendo errore "Impossibile aggiungere o aggiornare una riga secondaria" - mysql, chiavi esterne

errore alterando la tabella, aggiungendo la chiave esterna di restrizione ottenendo errore "Impossibile aggiungere o aggiornare una riga secondaria" - mysql, chiavi esterne

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    |                |
+--------------+--------------+------+-----+---------+----------------+

Sto usando questa affermazione:

ALTER TABLE risponde AGGIUNGI CHIAVE STRANIERA (questions_id) REFERENZE domande (id);

ma ottengo questo errore:

ERRORE 1452 (23000): impossibile aggiungere o aggiornare una riga secondaria: un vincolo di chiave esterna non riesce (surveydb.#sql-df_32, CONSTRAINT #sql-df_32_ibfk_1 CHIAVE ESTERA (questions_id) RIFERIMENTI questions (id)) alla versione del server MySQL per la sintassi corretta da utilizzare vicino a "Domande DESCREBE" alla riga 1

risposte:

2 per risposta № 1

Hai almeno un valore di dati in answers.questions_id che non si verifica in questions.id.

Ecco un esempio di cosa intendo:

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`))

Puoi usare questo per confermare che ci sono valori non abbinati:

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