将外键设置为多个表

将外键设置为多个表

本文介绍了将外键设置为多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三张表Teacher,Student,ViewType

 表教师{
Id uniqueidentifier,
名称nvarchar
}


表学生{
Id uniqueidentifier,
名称nvarchar
}


table ViewType {
Id uniqueidentifier,
Type String
}




它包含了如何在ui中显示教师或学生的数据不应该在教师或学生表中模型。$ ​​b
$ b

是否有一种方法可以创建一个外键给两个表,其中一个键是从
强制执行的,只能从两个表中执行?
Thanks。

解决方案

不符合Declarative Referential Integrity限制。

你必须用触发器来实现这个。你需要在 ViewType 上的所有三个表( insert + update c $ c>,删除 + 更新在其他)。

$ p
$ b pre code> alter table学生添加约束FK外键(Id)引用ViewType (Id)
alter table老师添加约束FK外键(Id)引用ViewType(Id)




I have three tables Teachers, Student, ViewType

table Teachers{
  Id uniqueidentifier,
  Name nvarchar
}


table Student{
  Id uniqueidentifier,
  Name nvarchar
}


table ViewType{
  Id uniqueidentifier,
  Type String
}

Note: Let's say for the example that ViewType is not a regular look up table.
it contains data of how to present the Teacher or Student in the ui therefor shouldn't be in the Teacher or Studenttable model.

Is there a way to create a foreign key to two tables where a key is enforced to fromand only from the two tables?Thanks.

解决方案

Not with Declarative Referential Integrity constraints.

You would have to implement this with triggers; and you would need them on all three tables (insert + update on ViewType, delete + update on the others).

You could put the constraints the other way:

alter table Student add constraint FK foreign key (Id) references ViewType (Id)
alter table Teachers add constraint FK foreign key (Id) references ViewType (Id)

It isn't perfect (you could end up with a Student & Teacher referencing the same Id, which you would have to deal with), but it's probably the best you could do.

这篇关于将外键设置为多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:57