数据库设计 - 防止“房间”表的重复

时间:2011-01-28 09:10:21

标签: database sql-server-2005 sql-server-2008 database-design data-structures

嘿大家,我正在尝试为我的私人朋友创建一个数据库,并且由于我在开发数据库方面缺乏经验,我很难尝试建立一个我正在处理的数据库。基本上,我的问题是我的“房间”表与另一个名为“location”的表有关联;位置是您期望的一切(buildingID,streetAddress等),Room具有包含buildingId的外键。我希望我的“房间”表格具有基于buildingId的房间号码的唯一值。

为了给你一个更清晰的想法,我只需要修改我用来创建这些表格的脚本。

CREATE TABLE [dbo].[Location](
 [buildingId] [int] IDENTITY(1,1) NOT NULL,
 [streetAddress] [varchar](50) NOT NULL,
 [postalCode] [varchar](7) NOT NULL,
 [province] [varchar](30) NOT NULL,
 [city] [varchar](30) NOT NULL,
 CONSTRAINT [PK_Location] PRIMARY KEY CLUSTERED 
(
 [buildingId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [UN_postalCode] UNIQUE NONCLUSTERED 
(
 [postalCode] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [UN_streetAddress] UNIQUE NONCLUSTERED 
(
 [streetAddress] 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].[Room](
 [rmId] [int] IDENTITY(1,1) NOT NULL,
 [roomNum] [varchar](10) NOT NULL,
 [floor] [int] NOT NULL,
 [capacity] [int] NOT NULL,
 [permission] [bit] NOT NULL,
 [buildingId] [int] NOT NULL,
 CONSTRAINT [PK_Room_1] PRIMARY KEY CLUSTERED 
(
 [rmId] 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

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Room]  WITH CHECK ADD  CONSTRAINT [FK_Room_Location] FOREIGN KEY([buildingId])
REFERENCES [dbo].[Location] ([buildingId])
GO

ALTER TABLE [dbo].[Room] CHECK CONSTRAINT [FK_Room_Location]
GO

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:2)

表级唯一约束?

ALTER TABLE dbo.Room WITH CHECK ADD
    CONSTRAINT UQ_Room_RoomBuildingLocation UNIQUE (roomNum, buildingId)

这也可以是一个唯一的索引,它允许INCLUDE列