我想在1个表中添加3个外键,但InnoDB会出错。我可以自己添加第一个外键,但是其他2个键也会出现相同的错误。这是语法:
CREATE TABLE Lokalen(
Gebouw VARCHAR(20) not null,
Verdieping INT not null,
Lokaal VARCHAR (3) not null,
Beweging BOOLEAN,
Computer BOOLEAN,
primary key (Gebouw, Verdieping, Lokaal));
CREATE TABLE Reserveringen(
Gebouw VARCHAR(20) not null,
Verdieping INT not null,
Lokaal VARCHAR (3) not null,
Begintijd TIME not null,
Eindtijd TIME,
Datum DATE not null,
Reserveringsnummer int not null,
primary key (Reserveringsnummer),
foreign key (Gebouw) REFERENCES Lokalen(Gebouw),
foreign key (Verdieping) REFERENCES Lokalen(Verdieping),
foreign key (Lokaal) REFERENCES Lokalen(Lokaal));
希望你能提供帮助:)
答案 0 :(得分:1)
对于复合FOREIGN KEY,语法为
FOREIGN KEY (Gebouw, Verdieping, Lokaal)
REFERENCES Lokalen(Gebouw, Verdieping, Lokaal)
我强烈建议使用简单的代理键(如自动增量ID),Localen
中的PK和Reserveringen
中的FK。
为避免错误:
DROP TABLE IF EXISTS Lokalen;
DROP TABLE IF EXISTS Reserveringen;
CREATE TABLE Lokalen(
Gebouw VARCHAR(20) not null,
Verdieping INT not null,
Lokaal VARCHAR (3) not null,
Beweging BOOLEAN,
Computer BOOLEAN,
primary key (Gebouw, Verdieping, Lokaal));
CREATE TABLE Reserveringen(
Gebouw VARCHAR(20) not null,
Verdieping INT not null,
Lokaal VARCHAR (3) not null,
Begintijd TIME not null,
Eindtijd TIME,
Datum DATE not null,
Reserveringsnummer int not null,
primary key (Reserveringsnummer),
FOREIGN KEY (Gebouw, Verdieping, Lokaal)
REFERENCES Lokalen(Gebouw, Verdieping, Lokaal));
使用代理键的方式
DROP TABLE IF EXISTS Lokalen;
DROP TABLE IF EXISTS Reserveringen;
CREATE TABLE Lokalen(
Id Int Not null auto_increment PRIMARY KEY,
Gebouw VARCHAR(20) not null,
Verdieping INT not null,
Lokaal VARCHAR (3) not null,
Beweging BOOLEAN,
Computer BOOLEAN);
CREATE TABLE Reserveringen(
Id Int not null auto_increment PRIMARY KEY,
LokalenId Int not null,
Begintijd TIME not null,
Eindtijd TIME,
Datum DATE not null,
Reserveringsnummer int not null,
FOREIGN KEY (LokalenId)
REFERENCES Lokalen(Id));
答案 1 :(得分:0)
除此之外,您正在复制各种数据(您应该阅读规范化数据库(或“normaalvorm”:))...
您需要对要用作外键的行建立索引。见http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
InnoDB允许外键引用任何索引列或组 列。但是,在引用的表中,必须有一个索引 其中引用的列被列为的第一列 同样的顺序。
答案 2 :(得分:0)
您可以在创建表外添加:
Create Table Reserveringen(
.....
.....
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;