我有一张描述多对一关系的表,比如图片和相册之间的关系。我希望能够为每张专辑选择一张也只有一张图片作为专辑的封面图片。现在,表格是这样的:
AlbumID int primary key,
PictureID int,
IsCover bool
假设我不想更改整体架构(解决方案可能是将“覆盖”关系移动到另一个表,定义一对一关系,但最好不要更改已经通过添加另一个表来实现查询),有没有办法强制所有具有相同AlbumID BUT ONE的条目都将IsCover设置为false?
我正在寻找服务器端解决方案。我正在使用Microsoft SQL Server 2012.此处不能应用UNIQUE约束,否则我只能为每个专辑提供封面和非封面。我已经在我的应用程序中实现了检查,但我真的希望有一个额外的安全层。
提前致谢。
答案 0 :(得分:4)
可能唯一的过滤索引可能对您有所帮助:
create table AlbumPics (
AlbumID int not NULL,
PictureID int not NULL,
IsCover bit not NULL,
primary key clustered (AlbumID, PictureID)
)
create unique index UX_AlbumPics_CoverPic
on AlbumPics (AlbumID) where IsCover = 1
-- insert 3 pics for album 1, one of them is cover pic
insert into AlbumPics values
(1, 1, 0), (1, 2, 1), (1, 3, 0)
-- try to insert one more cover for album 1 - will fail
insert into AlbumPics values
(1, 4, 1)