SQL一对多关系表设计,正确的方法

时间:2018-05-10 08:57:33

标签: sql sql-server database database-design ddl

情节:我需要预订一个依赖于3种不同类型工厂的订单。 我有订单和工厂的单独表。现在我需要在Order和Booking Factory之间建立一对多的关系。

订单表:

CREATE TABLE [dbo].[tbl_OrderInformation](
[OrderInformationId] [int] IDENTITY(1,1) NOT NULL,
[OrderId] [int] NOT NULL,
[OrderNo] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_tbl_OrderInformation] PRIMARY KEY CLUSTERED 
(   [OrderInformationId] 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].[tbl_Factory](
[FactoryId] [int] IDENTITY(1,1) NOT NULL,
[FactoryName] [nvarchar](50) NOT NULL,
[FactoryType] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_tbl_Factory] PRIMARY KEY CLUSTERED 
(   [FactoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

样品订单数据

enter image description here

样本工厂数据

enter image description here

现在,订单依赖于多件服装,染色和印刷工厂。

假设订单C101依赖于服装-A,染色-A,印刷-A,印刷-B,印刷-C。 现在,我可以用两种方式设计OrderBooking表。

CREATE TABLE [dbo].[tbl_OrderBooking_1](
[OrderBookingId] [INT] IDENTITY(1,1) NOT NULL,
[OrderId] [INT] NOT NULL,
[FactoryId] [INT] NULL,
[FactoryType] [NVARCHAR](50) NULL,
CONSTRAINT [PK_tbl_OrderBooking_1] PRIMARY KEY CLUSTERED 
(
[OrderBookingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

这些数据如下所示: enter image description here

第二种方式,

CREATE TABLE [dbo].[tbl_OrderBooking_2](
[OrderBookingId] [INT] IDENTITY(1,1) NOT NULL,
[OrderId] [INT] NULL,
[garmentsFactoryId] [INT] NULL,
[dyeingFactoryId] [INT] NULL,
[printingFactoryId] [INT] NULL,
CONSTRAINT [PK_tbl_OrderBooking_2] PRIMARY KEY CLUSTERED 
(
[OrderBookingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

这里的数据看起来像, enter image description here

现在,哪种设计OrderBooking表的方法更准确,为什么? 请记住,工厂的类型固定为3,OrderBooking表随着时间的推移会变得非常大,因此往往会有大量的读写操作。

1 个答案:

答案 0 :(得分:0)

订单与优惠之间的链接表工厂将是最好的方法。

您将获得更好的性能,您可以在数字列上创建索引。

如果您有任何新工厂,那么它也可以毫无问题地插入。

链接表也可以帮助您与规范化规则保持一致。所以我的建议就是这样。