0

我想向 1 个表添加 3 个外键,但 InnoDB 给出了错误。我可以自己添加第一个外键,但是其他两个键也会出现同样的错误。这是语法:

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

希望你能帮忙:)

4

3 回答 3

1

for composite FOREIGN KEY, the syntax is

FOREIGN KEY (Gebouw, Verdieping, Lokaal) 
    REFERENCES Lokalen(Gebouw, Verdieping, Lokaal)

I would strongly advise to use a simple surrogate key (like an autoincrement id), as PK in Localen and FK in Reserveringen).

To avoid errors :

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

the way with surrogate keys

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));
于 2013-05-30T12:31:25.960 回答
0

除此之外,您正在复制各种数据(您应该阅读规范化数据库(或“normaalvorm”:))...

您需要在要用作外键的行上建立索引。见http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html

InnoDB 允许外键引用任何索引列或列组。但是,在引用的表中,必须有一个索引,其中引用的列按相同顺序列为第一列。

于 2013-05-30T12:39:33.017 回答
0

您可以在创建表之外添加:

Create Table Reserveringen(
.....
.....
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
于 2016-04-27T09:19:23.493 回答