[英]Reference one foreign key to multiple primary keys in SQL Server 2014
I have three tables in my database. 我的数据库中有三个表。
Inside GeneralNeeds
there is ProcessID
which needs to keep MedicalTestID
and SportTestID
GUID. 在
GeneralNeeds
内部, ProcessID
需要保留MedicalTestID
和SportTestID
GUID。
As soon as I insert an existing GUID from either tables I get "Conflict" error message which I believe it means the given GUID doesn't exist in the other table. 只要从任一表中插入现有GUID,我就会收到“Conflict”错误消息,我相信这意味着另一个表中不存在给定的GUID。
For example: If I insert the GUID from MedicalTest
then it will tell me that the SportTest
doesn't have the given GUID. 例如:如果我从
MedicalTest
插入GUID,那么它会告诉我SportTest
没有给定的GUID。
Is it possible to reference multiple keys to one column? 是否可以将多个键引用到一列?
The design I'd recommend here is a table/sub-table solution. 我在这里推荐的设计是表/子表解决方案。 What that means is, introduce a 4th table,
Test
. 这意味着,引入第4个表,
Test
。 The Test
table just serves as a table that links all the different test types together. Test
表只是用作将所有不同测试类型链接在一起的表。 If you're familiar with Object Oriented Programming, think of it as a base type. 如果您熟悉面向对象编程,请将其视为基本类型。 So essentially, your
ProcessID
points to Test
which then points to one of the specific test types (SportsTest, MedicalTest, WhateverTest). 基本上,你的
ProcessID
指向Test
,然后指向一个特定的测试类型(SportsTest,MedicalTest,WhateverTest)。 If you like, you could also include a Type
in the Test
table to help you know which type of test it is. 如果您愿意,还可以在
Test
表中包含一个Type
,以帮助您了解它是哪种类型的测试。 There is a key thing here: In the MedicalTest
and SportsTest
table, the primary key (say MedicalTestID
) is also a foreign key that points to the TestID
in Test
. 这里有一个关键的问题:在
MedicalTest
和SportsTest
表中,主键(比如MedicalTestID
)也是一个指向Test
TestID
的外键。 In this way you can use a single column in your GeneralNeeds
because the reference is to a single table type, Test
. 通过这种方式,您可以在
GeneralNeeds
使用单个列,因为引用的是单个表类型Test
。 Since Test
and the corresponding MedicalTest
or SportsTest
would have the same primary key, you can easily do the joins you need to do the query. 由于
Test
和相应的MedicalTest
或SportsTest
具有相同的主键,因此您可以轻松地执行查询所需的连接。
Here is a sample diagram illustrating it: 以下是说明它的示例图:
Simple example: Say you have a MedicalTest
with ID of 1 (let's forget GUIDs for a minute to make it easier to read) Then you'd also have a record in Test
with an ID of 1. Then the ProcessID
of 1 really points to the Test
record which you could then join to the MedicalTest
record. 简单的例子:假设您有一个ID为1的
MedicalTest
(让我们忘记一分钟的GUID以使其更容易阅读)然后您还在Test
有一个ID为1的记录。然后ProcessID
为1真正指向在Test
记录,然后您可以加入到MedicalTest
记录。
If you're still confused let me know and I'll try to add a bit more detail but hopefully this gets you going in a direction that works. 如果您仍然感到困惑,请告诉我,我会尝试添加更多细节,但希望这会让您朝着有效的方向前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.