我刚开始使用SQL,我有一个要做的事情,它涉及到SQL表的关系方案。
我对如何表示以下内容存在很大疑问: 我有“原始”表,由以下SQL表示:
create table Original (
idB char(10) not null unique,
tituloM varchar(255) not null,
primary key (idB, tituloM),
foreign key (idB, tituloM) references Musica on delete cascade on update cascade
);
我现在必须代表具有以下关系表示的“Live”表:
Live(idB; tituloM; data; hora; tituloMO),其中idB
和tituloMO
是“Original”的外键。我的疑问是,我们在“原始”表格中没有“tituloMO”。我怎么能代表这个呢?目前我的“原始”表格如下:
create table Live (
idB char(10) not null unique,
tituloM varchar(255) not null,
/* date goes here */
/* time goes here */
tituloMO varchar(255) not null,
primary key (idB, tituloM),
foreign key (idB, tituloM) references Musica on delete cascade on update cascade,
foreign key (idB, data, hora) references Concerto on delete cascade on update cascade,
foreign key (idB, tituloMO)
);
如何正确表示tituloMO
字段?
答案 0 :(得分:1)
您需要知道tituloMO
表中Original
字段对应的内容。它不需要是同一个名字。
例如,您可以将Live.tituloMO
映射到Original.tituloM
我不知道你有什么DBMS,你的外键语法看起来好像缺少父表字段。
这是您在Oracle中输入的方式。
foreign key (idB, tituloMO) references Original(idB, tituloM) on delete...
答案 1 :(得分:0)
当您进行FOREIGN KEY
引用时,您不需要相应的列具有相同的名称,只需要兼容的数据类型。
所以,你的约束是:
create table Original (
idB char(10) not null unique,
tituloM varchar(255) not null,
primary key (idB, tituloM),
foreign key (idB, tituloM)
references Musica (idB, tituloM) --- you need these, too
on delete cascade
on update cascade
);
create table Live (
idB char(10) not null unique,
tituloM varchar(255) not null,
/* date goes here */
/* time goes here */
tituloMO varchar(255) not null,
primary key (idB, tituloM),
foreign key (idB, tituloM)
references Musica (idB, tituloM) --- and these
on delete cascade
on update cascade,
foreign key (idB, data, hora)
references Concerto (idB, data, hora) --- and these
on delete cascade
on update cascade,
foreign key (idB, tituloMO)
references Original (idB, tituloM) --- this is an assumption
on delete cascade --- based on the datatypes
on update cascade,
);