Gerade RTM:
https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
prüfen diese Geige:
http://sqlfiddle.com/#!9/9fb10
create table a (id int NOT NULL AUTO_INCREMENT, title varchar(20), PRIMARY KEY (`id`));
create table b (id int NOT NULL AUTO_INCREMENT, title varchar(20), PRIMARY KEY (`id`),
a_id int,
CONSTRAINT a_id FOREIGN KEY (a_id) REFERENCES a(id) )ENGINE=INNODB ;
create table c (id int NOT NULL AUTO_INCREMENT, title varchar(20), PRIMARY KEY (`id`),
a_id int,
CONSTRAINT a_id_C FOREIGN KEY (a_id) REFERENCES a(id) )ENGINE=INNODB ;
#CONSTRAINT a_id FOREIGN KEY (a_id) REFERENCES a(id) )ENGINE=INNODB ;
create table d (id int NOT NULL AUTO_INCREMENT, title varchar(20), PRIMARY KEY (`id`),
a_id int,
FOREIGN KEY (a_id) REFERENCES a(id) )ENGINE=INNODB ;
Die Idee CONSTRAINT
soll einen eindeutigen Namen für die gesamte Datenbank erstellen. Wenn Sie also jemals den Index CONSTRAINT a_id
erstellt haben, überprüft die Datenbank jeden Versuch, einen Index mit demselben Namen in einer anderen Tabelle zu erstellen, und lehnt ihn ab.
In Beispiel oben Wenn Sie
#CONSTRAINT a_id FOREIGN KEY (a_id) REFERENCES a(id)
für c
Tabelle Kommentar- werden versuchen, MySQL-Server eine Fehlermeldung aufmerksam, weil a_id
bereits für b
Tabelle verwendet wurde.
Und zur gleichen Zeit, wenn Sie einfach nicht CONSTRAINT
verwenden, können Sie Index mit dem gleichen Namen wie für Tabelle d
angezeigt erstellen.
'CONSTRAINT' ist ein optionales Schlüsselwort, das Teil der Standard-SQL-Syntax ist. Mit anderen Datenbanken können Sie andere Arten von Einschränkungen erstellen, aber MySQL hat nur Fremdschlüssel. – Barmar