我有三张桌子:
CREATE TABLE Items (
[ItemId] int not null identity(1,1)
,[ItemName] nvarchar(250) not null
-- other colums related to item
)
CREATE TABLE Categories (
[CategoryId] int not null identity(1,1)
,[CategoryName] nvarchar(50) not null
-- other colums related to category
)
CREATE TABLE ItemCategories (
[ItemId] int not null
,[CategoryId] int not null
,CONSTRAINT [PK_ItemCategories] PRIMARY KEY CLUSTERED ( [ItemId], [CategoryId] )
,CONSTRAINT [FK_ItemCategories_Items] FOREIGN KEY ( [ItemId] )
REFERENCES Items ( [ItemId] )
ON DELETE CASCADE --ON UPDATE CASCADE
,CONSTRAINT [FK_ItemCategories_Categories] FOREIGN KEY ( [CategoryId] )
REFERENCES Categories ( [CategoryId] )
ON DELETE CASCADE --ON UPDATE CASCADE
)
经典问题,但让我感到困惑。
[ItemCategories]表是存储[ItemId]和[CategoryId]之间关系的唯一表。
我想要的是当从[Items]或[Categories]中删除记录时,从[ItemCategories]中删除记录。
其他人是否可以将注意力放在代码上以查看我是否错误地声明了某些内容?欢呼声。
答案 0 :(得分:1)
该代码看起来很好。
CREATE TABLE Items (
[ItemId] int not null identity(1,1) primary key
,[ItemName] nvarchar(250) not null
-- other colums related to item
)
CREATE TABLE Categories (
[CategoryId] int not null identity(1,1) primary key
,[CategoryName] nvarchar(50) not null
-- other colums related to category
)
CREATE TABLE ItemCategories (
[ItemId] int not null
,[CategoryId] int not null
,CONSTRAINT [PK_ItemCategories] PRIMARY KEY CLUSTERED ( [ItemId], [CategoryId] )
,CONSTRAINT [FK_ItemCategories_Items] FOREIGN KEY ( [ItemId] )
REFERENCES Items ( [ItemId] )
ON DELETE CASCADE --ON UPDATE CASCADE
,CONSTRAINT [FK_ItemCategories_Categories] FOREIGN KEY ( [CategoryId] )
REFERENCES Categories ( [CategoryId] )
ON DELETE CASCADE --ON UPDATE CASCADE
)
go
insert into items(ItemName) values ('itema')
insert into Categories(CategoryName) values ('categorya')
insert into ItemCategories(ItemId,CategoryId) values (1,1)
go
delete from items
go
select * from ItemCategories --empty