dan*_*ans 4 sql-server-2005 foreign-key database-design
我有一个articles引用categories表的表。我像这样定义外键:
constraint fk_categoryid foreign key (categoryid) references categories (categoryid)
on update no action
on delete no action
Run Code Online (Sandbox Code Playgroud)
是否可以在外键定义中限制可以基于categories表中另一列引用的类别?例如,假设表中有一个hasarticles列categories。我希望将外键约束限制在hasarticles = true.
不,这是不可能的。
我可能会创建一个单独的表categoriesWithArticles来保存相关的categoryids(而不是拥有标志),并让 FK 引用该表。
另一种更复杂的方法来强制执行它并保留该列是
CREATE TABLE categories
(
categoryId int primary key,
hasarticles bit not null,
unique(categoryId, hasarticles)
)
CREATE TABLE articles
(
categoryId int,
hasarticles as cast (1 as bit) persisted,
FOREIGN KEY (categoryId, hasarticles) REFERENCES categories(categoryId, hasarticles)
)
Run Code Online (Sandbox Code Playgroud)
但这需要创建技术上冗余的唯一约束以及表中的附加持久列articles。