一对多的关系怎么建立?

fish1201 2003-10-09 12:01:06
比如有两张表,一张表的主键约束另一张表的4个字段,怎么样建立他们的关系?
...全文
110 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengdali 2003-10-09
  • 打赏
  • 举报
回复
举例:


create table 主表
(商品编号 varchar(20) not null PRIMARY KEY CLUSTERED ,
商品名称 varchar(20) UNIQUE NONCLUSTERED ,
数量 int
)


create table 主表1
(商品编号 varchar(20) not null PRIMARY KEY CLUSTERED ,
商品名称 varchar(20) UNIQUE NONCLUSTERED ,
数量 int
)


create table 次表
(商品编号 varchar(20) not null ,
商品名称 varchar(20) not null
primary key ( 商品编号,商品名称 )
FOREIGN KEY (商品编号) REFERENCES 主表 (商品编号)
ON DELETE CASCADE ON UPDATE CASCADE ,
FOREIGN KEY ( 商品名称) rEFERENCES 主表1 (商品编号)
ON DELETE CASCADE ON UPDATE CASCADE ,
供应商 varchar(20)
)



insert 主表 select '003','aa',77

insert 主表1 select '104','bb',17

insert 次表 select '003','104','y'

update 主表1 set 商品编号='105'

update 主表 set 商品编号='004'


select * from 次表
lynx1111 2003-10-09
  • 打赏
  • 举报
回复
一样的建阿
pengdali 2003-10-09
  • 打赏
  • 举报
回复
alter table 从表
add constraint fk_mylocation_myname foreign key(列名)references 主表(列名)
txlicenhe 2003-10-09
  • 打赏
  • 举报
回复
eg:
alter table 表2
add constraint fk_mylocation_myname foreign key(字段1)references 表1(字段1)
on update cascade on delete cascade
alter table 表2
add constraint fk_mylocation_myname foreign key(字段2)references 表1(字段1)
on update cascade on delete cascade
alter table 表2
add constraint fk_mylocation_myname foreign key(字段3)references 表1(字段1)
on update cascade on delete cascade
alter table 表2
add constraint fk_mylocation_myname foreign key(字段4)references 表1(字段1)
on update cascade on delete cascade
Wally_wu 2003-10-09
  • 打赏
  • 举报
回复
使用外部键(foreign key)
create table mastertable
(
userid varchar(6),
username varchar(70),
constraint pk_id primary key(userid)
)

create table HouseTable
(
userid varchar(6),
department varchar(70),
constraint pk_id primary key(userid)
constraint fk_mastertable_id foreign key(userid)references mastertable(userid)
)

bitfubin 2003-10-09
  • 打赏
  • 举报
回复
建议在视图中拉线。。。

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧