外键问题

时间:2014-09-07 17:30:25

标签: sql sql-server

由于我是SQL Server的新手,我想我需要一点帮助......因为我已经多次重写了以下代码,所以可能还有其他错误,抱歉。删除了' GO'现在。

问题:

我不知道如何从" model"创建外键。在Cars表中Model

我的破码:

create table [Cars]
(
   [id] [int] not null primary key identity,
   [name] [nvarchar](50) not null,
   [weight] [int] not null,
   [length] [int] not null,
   [model] [nvarchar](50) not null,
   [color] [nvarchar](50) not null
);

create table [Colors]
(
   [id] [int] not null primary key identity,
   [name] [nvarchar](50) not null
);

create table [Model] 
(
    [id] [int] primary key not null identity,
    [name] [nvarchar](50) not null
);

insert into Cars(name, weight, length, model, color)
values('Ferrari', '1500', '4000', '360', 'Red');

insert into Colors values('Red');
insert into Colors values('Blue');
insert into Colors values('Yellow');

insert into Model values('Volvo');
insert into Model values('Fiat');
insert into Model values('Saab');

alter table Model
add foreign key (id)
references Cars(id)

alter table Colors
add foreign key (id)
references Cars(id)

3 个答案:

答案 0 :(得分:0)

我建议不要将所有主键命名为相同(ID),因为这会在创建外键时遇到问题。

您的表格Cars的{​​{1}}为model,如果您使用的是代理键,则不需要nvarchar。将数据类型更改为int,将名称更改为model_id并向表中添加约束:

ALTER TABLE Cars
ADD CONSTRAINT FK$Model$id FOREIGN KEY (model_id)
REFERENCES Model(id)

正如其他人所提到的,您在Colors表中使用外键也是不正确的。

答案 1 :(得分:0)

这段代码设法解决了我认为的问题,你们这里的几个人确实做出了贡献,谢谢。

alter table Cars
add constraint fk_colors foreign key (colorid)
references colors([id])

答案 2 :(得分:-1)

--Add column in Model as Car_ID
--then use

ALTER TABLE Model
ADD CONSTRAINT FK_CarsID FOREIGN KEY(Car_ID) REFERENCES Cars(ID)