在SQL Server数据库中建立一对多关系时,我有点困惑。我无法弄清楚如何创建多个表并为这一对多关系放置数据
答案 0 :(得分:2)
创建表格并定义关系:
create table the_one_entity
(
id integer primary key,
some_data varchar(100)
);
create table the_many_entity
(
id integer primary key,
the_one_id integer not null,
some_more_data varchar(100),
-- this establishes the relationship
foreign key fk_one_to_many (the_one_id)
references the_one_entity (id)
);
关系是通过引用the_one_id
the_one_entity
定义的
如何输入数据。
首先插入"一个"的行。实体:
insert into the_one_entity
(id, some_data)
values
(1, 'First Thing'),
(2, 'Second Thing');
然后插入相关实体的行:
insert into the_many_entity
(id, the_one_id, some_more_data)
values
(1, 1, 'First detail for the First Thing'),
(2, 1, 'Second detail for the First Thing'),
(3, 1, 'Third detail for the First Thing'),
(4, 2, 'First detail for the Second Thing'),
(5, 2, 'Second detail for the Second Thing');