MySQL “ERRORE 1005 (HY000): Impossibile creare la tabella 'pippo # sql-12c_4.' (Errno: 150)”
-
04-10-2019 - |
Domanda
I stava lavorando sulla creazione di alcune tabelle in foo
banca dati, ma ogni volta che finisce con errno 150 per quanto riguarda la chiave esterna. In primo luogo, ecco il mio codice per la creazione di tabelle:
CREATE TABLE Clients
(
client_id CHAR(10) NOT NULL ,
client_name CHAR(50) NOT NULL ,
provisional_license_num CHAR(50) NOT NULL ,
client_address CHAR(50) NULL ,
client_city CHAR(50) NULL ,
client_county CHAR(50) NULL ,
client_zip CHAR(10) NULL ,
client_phone INT NULL ,
client_email CHAR(255) NULL ,
client_dob DATETIME NULL ,
test_attempts INT NULL
);
CREATE TABLE Applications
(
application_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
instructor_id CHAR(10) NOT NULL ,
car_id CHAR(10) NOT NULL ,
application_date DATETIME NULL
);
CREATE TABLE Instructors
(
instructor_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
instructor_name CHAR(50) NOT NULL ,
instructor_address CHAR(50) NULL ,
instructor_city CHAR(50) NULL ,
instructor_county CHAR(50) NULL ,
instructor_zip CHAR(10) NULL ,
instructor_phone INT NULL ,
instructor_email CHAR(255) NULL ,
instructor_dob DATETIME NULL ,
lessons_given INT NULL
);
CREATE TABLE Cars
(
car_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
engine_serial_num CHAR(10) NULL ,
registration_num CHAR(10) NULL ,
car_make CHAR(50) NULL ,
car_model CHAR(50) NULL
);
CREATE TABLE Offices
(
office_id INT NOT NULL ,
office_address CHAR(50) NULL ,
office_city CHAR(50) NULL ,
office_County CHAR(50) NULL ,
office_zip CHAR(10) NULL ,
office_phone INT NULL ,
office_email CHAR(255) NULL
);
CREATE TABLE Lessons
(
lesson_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
date DATETIME NOT NULL ,
time DATETIME NOT NULL ,
milegage_used DECIMAL(5, 2) NULL ,
progress CHAR(50) NULL
);
CREATE TABLE DrivingTests
(
test_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
test_date DATETIME NOT NULL ,
seat_num INT NOT NULL ,
score INT NULL ,
test_notes CHAR(255) NULL
);
ALTER TABLE Clients ADD PRIMARY KEY (client_id);
ALTER TABLE Applications ADD PRIMARY KEY (application_id);
ALTER TABLE Instructors ADD PRIMARY KEY (instructor_id);
ALTER TABLE Offices ADD PRIMARY KEY (office_id);
ALTER TABLE Lessons ADD PRIMARY KEY (lesson_num);
ALTER TABLE DrivingTests ADD PRIMARY KEY (test_num);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Instructors FOREIGN KEY (instructor_id) REFERENCES Instructors (instructor_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY (car_id) REFERENCES Cars (car_id);
ALTER TABLE Lessons ADD CONSTRAINT FK_Lessons_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Cars ADD CONSTRAINT FK_Cars_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Clients ADD CONSTRAINT FK_DrivingTests_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
Questi sono gli errori che ottengo:
mysql> ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY
(car_id) REFERENCES Cars (car_id);
ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)
I corse SHOW ENGINE INNODB STATUS
che dà una descrizione di errore più dettagliato:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100509 20:59:49 Error in foreign key constraint of table foo/#sql-12c_4:
FOREIGN KEY (car_id) REFERENCES Cars (car_id):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
------------
Ho cercato in giro su StackOverflow e altrove in linea - sono imbattuto in un post sul blog utile qui con indicazioni su come risolvere questo errore - ma non riesco a capire che cosa sta andando male. Qualsiasi aiuto sarebbe apprezzato!
Soluzione
Si dovrebbe fare car_id una chiave primaria in auto.
Altri suggerimenti
Nota:. Ho avuto lo stesso problema, ed è stato perché il campo di riferimento era in un confronto diverso nelle 2 tabelle differenti (avevano esattamente lo stesso tipo)
assicurarsi che tutti i campi di riferimento hanno lo stesso tipo e la stessa collazione!
Controllare che entrambe le tabelle hanno lo stesso motore. Per esempio, se si dispone di:
CREATE Table FOO ();
e
CREATE Table BAR () ENGINE=INNODB;
Se si tenta di creare un vincolo da tavolo BAR al tavolo FOO, non funzionerà su alcune versioni di MySQL.
Risolvere il problema seguendo:
CREATE Table FOO () ENGINE=INNODB;
Sottile, ma questo errore mi ha fatto perché ho dimenticato di dichiarare una colonna smallint unsigned come per abbinare il riferimento, tabella esistente che era "smallint unsigned". Avere uno non firmato e non privo di firma digitale causato MySQL per evitare che la chiave esterna di essere creata sulla nuova tabella.
id smallint(3) not null
non corrisponde, per il bene di chiavi esterne,
id smallint(3) unsigned not null
ho ottenuto questo errore completamente inutile e poco informativi quando ho provato a:
ALTER TABLE `comments` ADD CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
Il mio problema era nella mia tabella di commenti, id_utente è stata definita come:
`user_id` int(10) unsigned NOT NULL
Quindi ... nel mio caso, il problema era con il conflitto tra NOT NULL, e ON DELETE SET NULL.
Inoltre, sia le tabelle devono avere lo stesso set di caratteri.
per esempio
CREATE TABLE1 (
FIELD1 VARCHAR(100) NOT NULL PRIMARY KEY,
FIELD2 VARCHAR(100) NOT NULL
)ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_bin;
a
CREATE TABLE2 (
Field3 varchar(64) NOT NULL PRIMARY KEY,
Field4 varchar(64) NOT NULL,
CONSTRAINT FORIGEN KEY (Field3) REFERENCES TABLE1(FIELD1)
) ENGINE=InnoDB;
fallirà perché hanno diversi set di caratteri. Questo è un altro fallimento sottile in cui MySQL restituisce lo stesso errore.
io uso Ubuntu Linux, e nel mio caso l'errore è stato causato dalla sintassi dichiarazione non corretta (che ho scoperto digitando perror 150 al terminal, che dà
MySQL codice di errore 150: vincolo di chiave esterna è formata in modo non corretto
La modifica della sintassi della query da
alter table scale add constraint foreign key (year_id) references year.id;
a
alter table scale add constraint foreign key (year_id) references year(id);
riparato.
Il campo di riferimento deve essere una "chiave" nella tabella di riferimento, non necessariamente una chiave primaria. Così il "car_id" dovrebbe essere o una chiave primaria o essere definita con NOT NULL e unici vincoli nella tabella "Cars".
E inoltre, entrambi i campi devono essere dello stesso tipo e di confronto.
Inoltre ho ricevuto questo errore (per diversi tavoli) con gli errori di vincolo e MySQL di collegare e scollegare quando si tenta di importare un intero database (~ 800 MB). Il mio problema è il risultato di Il server MySQL pacchetti massime consentite di essere troppo bassa. Per risolvere questo (Mac):
- /private/etc/my.conf Inaugurato
- In # Il server MySQL , cambiato
max_allowed_packet
da 1M a 4M (Potrebbe essere necessario sperimentare con questo valore.) - Restarted MySQL
La banca dati importati con successo dopo.
Si noti Sono in esecuzione MySQL 5.5.12 per Mac OS X (x86 a 64 bit).
controllare per rendere il campo si fa riferimento ad una corrispondenza esatta con la chiave esterna, nel mio caso è rimasto senza segno e l'altro è stato firmato in modo Ho appena cambiato loro di abbinare e questo ha funzionato
ALTER TABLE customer_information
Aggiungi vincolo fk_customer_information1
FOREIGN KEY (user_id
)
RIFERIMENTI users
(id
)
ON DELETE CASCADE
ON UPDATE CASCADE
Risolto:
Verificare che primary_key e foreign_key sono corrispondenza esatta con i tipi di dati. Se uno è firmato un altro non firmato, sarà riuscito. La buona pratica è quella di assicurarsi che entrambi sono unsigned int.
Io sto usando un nome duplicato chiave esterna.
Rinominare il nome FK risolto il mio problema.
Chiarimento:
Entrambe le tabelle hanno un vincolo chiamato PK1, FK1, ecc li Rinominare / rendendo i nomi unica risolto il problema.
La colonna di riferimento deve essere un indice di una singola colonna o la prima colonna di indice a più colonne, e lo stesso tipo e la stessa collazione.
I miei due tabelle hanno le regole di confronto diverse. Si può dimostrare, mediante emissione di stato tabella show come table_name
e collazione può essere modificata mediante l'emissione di alter Converti tabella table_name
per set di caratteri utf8.
tutto, ho risolto un problema e ha voluto condividere:
ho avuto questo errore <> Il problema era in quella nella mia dichiarazione:
ALTER TABLE system_registro_de_modificacion add chiave esterna(Usuariomodificador_id) RIFERIMENTI Usuario (id) su Elimina limitare;
I aveva erroneamente scritto l'involucro: funziona in Windows WAMP, ma in Linux MySQL è più severo con l'involucro, così scrivendo "Usuario" invece di "usuario" (involucro esatto), ha generato l'errore, ed è stato corretto semplicemente cambiando l'involucro.