这里不能加外键吗?

时间:2018-02-21 00:09:10

标签: mysql sql foreign-keys

所以我正在尝试创建表格,我不能为我的生活理解为什么我一直得到并且错误说“不能将外键添加到约束中”。

类型相同,父类是主键,它们的NULL是相同的。

问题出现在CDSingers的create table的行中,其中显示:

foreign key (track_num) references CDTracks (track_num),

(它快要结束了) 它是唯一不会被创建的表,因为这一行。 请帮忙。 (其他一些表已被省略,因为它们没有连接)

create table CD 
(
num int NOT NULL, 
producer varchar(100) NOT NULL, 
cd_number varchar(100) NOT NULL, 
title varchar(100) NOT NULL, 
type varchar(100) , 
band_name varchar(100) , 
production_date DATE NOT NULL, 
price double CHECK (price >= 0),
foreign key (type) references MusicType (type), 
foreign key (band_name) references Band (band_name),
primary key (num),
unique (producer, cd_number)
);

create table CDTracks
(
num int NOT NULL,
track_num int NOT NULL,
song_name varchar(100) NOT NULL,
minute int NOT NULL,
foreign key (num) references CD (num),
primary key (num, track_num)
);

create table Singer
(
id int NOT NULL,
singer_firstname varchar(100) NOT NULL,
singer_lastname varchar(100) NOT NULL,
primary key (id)
);

create table CDSingers
(
num int NOT NULL,
track_num int NOT NULL,
singer_id int NOT NULL,
foreign key (num) references CDTracks (num),
foreign key (track_num) references CDTracks (track_num),
foreign key (singer_id) references Singer (id),
primary key (num, track_num, singer_id)
);

1 个答案:

答案 0 :(得分:2)

您声明复合外键如下:

foreign key (num, track_num) references CDTracks (num, track_num),