简体   繁体   English

SQL Server中的外键约束

[英]Foreign Key constraints in SQL Server

I have a database scheme with versioning data rows, eg Table Person has the columns 我有一个带有数据行版本控制的数据库方案,例如Table Person有列

id (int, PK)
name (String)
current (Bool)
firstid (int)

Current is 0 for previous data, 1 for the latest entry. Current为0,以前的数据为1,最新的数据为1。 All rows for the same entity have the same FirstID , which points to the first ID of the set. 同一实体的所有行都具有相同的FirstID ,它指向集合的第一个ID

Referencing table: Adress with the same principle: 参考表:具有相同原理的Adress

id (int, PK)
street (String)
person_id (int)
current (Bool)
firstid (int)

Person_id points to patient.firstid . Person_idpatient.firstid So firstid is never unique, only if current=1 因此,仅当current=1firstid才是唯一的

My problem is: I would like to add referential integrity to my tables, but this only works, if the referenced column ( patient.firstid ) is unique... 我的问题是:我想在我的表中添加参照完整性,但这仅在所参照的列( patient.firstid )是唯一的时才有效...

You should look at refactoring your table structure. 您应该查看重构表结构。 But to keep within the current structure, add a self-referencing foreign key to person 但是要保持当前结构不变,请向人员添加自引用外键

firstid references person(id) firstid引用人(id)

Then, reference the "base person" from the address table 然后,从地址表中引用“基本人员”

address.person_id references person(id) -- which should ONLY store a link to the first id address.person_id引用person(id)-仅应存储指向第一个id的链接

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; 一个FOREIGN KEY约束不必仅链接到另一个表中的PRIMARY KEY约束。 it can also be defined to reference the columns of a UNIQUE constraint in another table. 也可以定义它引用另一个表中的UNIQUE约束的列。 A FOREIGN KEY constraint can contain null values; FOREIGN KEY约束可以包含空值; however, if any column of a composite FOREIGN KEY constraint contains null values, then verification of the FOREIGN KEY constraint will be skipped. 但是,如果复合FOREIGN KEY约束的任何列包含空值,那么将跳过FOREIGN KEY约束的验证。

Data from two related tables can be combined even if no PRIMARY KEY or FOREIGN KEY constraints are defined between the tables, but a foreign key relationship between two tables indicates that the two tables have been optimized to be combined in a query that uses the keys as its criteria. 即使在表之间未定义PRIMARY KEY或FOREIGN KEY约束,也可以合并来自两个相关表的数据,但是两个表之间的外键关系表明这两个表已经过优化,可以在将键用作它的标准。

reference http://msdn.microsoft.com/en-us/library/aa933117(v=sql.80).aspx 参考http://msdn.microsoft.com/zh-cn/library/aa933117(v=sql.80).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM