唯一键(非主键)可以是声明性外键约束的父键

时间:2009-08-04 03:41:59

标签: sql

天真的问题,回答“不”,我相信,但仍然想问。

Table_parent

pk_parent_surrogate  
parent_natural_unique_key


Table_child

pk_child_surrogate
child_natural_NOT_unique

主数据库供应商之间唯一可能的声明性关系是

pk_parent_surrogate ----------<  pk_child_surrogate

我们不能为对象

设置声明性约束或外键
parent_natural_unique_key -------< child_natural_NOT_unique

2 个答案:

答案 0 :(得分:2)

我的答案基于我的MS SQL知识 - 尽管我认为同样的答案对于ANSI标准也是正确的,但我并非百分之百确定......

是 - 只要您对父表中要用作密钥的锚列的列有唯一约束,就可以执行此操作。

  

您可以创建FOREIGN KEY约束作为部分   创建表时的表定义。   如果表已存在,则可以添加   FOREIGN KEY约束,前提是   FOREIGN KEY约束链接到现有的   PRIMARY KEY约束或UNIQUE约束   另一个,或相同的表。表可以包含   多个FOREIGN KEY约束。

作为这种关键的一个例子......

use tempdb

CREATE TABLE parent(
    pk int identity primary key, 
    candidate_key int unique not null)

CREATE TABLE child(
    pk int identity primary key, 
    join_key int references parent(candidate_key))

有关详细信息,请参阅here

答案 1 :(得分:0)

尝试这样的代码:

create table testunique (id int identity(1,1) primary key, otherid int)
go
create unique index ixOther on testunique(otherid)
go
create table testFK (id int identity(1,1) primary key, someid int)
go
alter table testFK add constraint fkTest foreign key (someid) references testunique(otherid)

罗布