在SQL数据库中创建这些表之间关系的正确方法是什么?

时间:2017-06-09 13:21:03

标签: sql database database-schema rdbms

我有三张桌子:办公室,子办公室和销售。每个办事处都拥有多个子办公室,办公室和子办事处都销售产品。我应该如何设计我的销售表来存储销售的办公室或子办公室?

我正在考虑使用由office_id和suboffice_id构成的复合外键(其中suboffice_id可能为null,在这种情况下,在办公室进行了销售) 这是设计数据库的正确方法吗? 我还在考虑有两个销售表:办公室和子办公室。但在我看来,这会让事情变得更难......

更新

销售可以是不同类型,因此它们需要不同的表。并且会有一张桌子' SALES'这将存储销售类型及其制作地点

2 个答案:

答案 0 :(得分:3)

从物业角度来看,您的子办事处与办公室的声音相同。下面是Office表包含ParentOffice外键的表格设计图。

enter image description here

这是创建这些表的SQL:

CREATE TABLE [dbo].[Office](
    [OfficeId] [int] NOT NULL,
    [ParentOfficeId] [int] NULL,
    [MoreStuff] [nvarchar](50) NULL,
 CONSTRAINT [PK_Office] PRIMARY KEY CLUSTERED 
(
    [OfficeId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Office]  WITH CHECK ADD  CONSTRAINT [FK_Office_Office] FOREIGN KEY([ParentOfficeId])
REFERENCES [dbo].[Office] ([OfficeId])
GO

ALTER TABLE [dbo].[Office] CHECK CONSTRAINT [FK_Office_Office]
GO

CREATE TABLE [dbo].[Product](
    [ProductId] [int] NOT NULL,
    [MoreStuff] [nvarchar](50) NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
    [ProductId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Sale](
    [SaleId] [int] NOT NULL,
    [ProducitId] [int] NOT NULL,
    [OfficeId] [int] NOT NULL,
 CONSTRAINT [PK_Sale] PRIMARY KEY CLUSTERED 
(
    [SaleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Sale]  WITH CHECK ADD  CONSTRAINT [FK_Sale_Office] FOREIGN KEY([OfficeId])
REFERENCES [dbo].[Office] ([OfficeId])
GO

ALTER TABLE [dbo].[Sale] CHECK CONSTRAINT [FK_Sale_Office]
GO

ALTER TABLE [dbo].[Sale]  WITH CHECK ADD  CONSTRAINT [FK_Sale_Sale] FOREIGN KEY([ProducitId])
REFERENCES [dbo].[Product] ([ProductId])
GO

ALTER TABLE [dbo].[Sale] CHECK CONSTRAINT [FK_Sale_Sale]
GO

答案 1 :(得分:1)

假设OFFICESUBOFFICE共享许多相同的属性,假设这样做的一种方法是删除SUBOFFICE表并向PARENT_OFFICE_ID列添加OFFICE列{1}}表。根据这种设计,办公室和分办事处之间的区别在于PARENT_OFFICE_ID是否为空。然后,SALES可以只有一个OFFICE_ID列,可以引用任何一种办公室。