Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 引用的表中没有PK。为什么?_Sql_Tsql - Fatal编程技术网

Sql 引用的表中没有PK。为什么?

Sql 引用的表中没有PK。为什么?,sql,tsql,Sql,Tsql,我使用以下T-SQL创建3个SQL表: create table dbo.Posts ( Id int identity not null constraint PK_Posts_Id primary key clustered (Id), Active bit not null constraint DF_Posts_Active default (0) ); create table dbo.PostsLocalized ( Id int not null,

我使用以下T-SQL创建3个SQL表:

create table dbo.Posts
(
  Id int identity not null 
    constraint PK_Posts_Id primary key clustered (Id),
  Active bit not null 
    constraint DF_Posts_Active default (0)
);

create table dbo.PostsLocalized
(
  Id int not null, 
  Culture int not null
    constraint CK_PostsLocalized_Culture check ([Culture] in ('1', '2', '3')),
  [Text] nvarchar (200) not null,
    constraint PK_PostsLocalized_Id_Culture primary key clustered (Id, Culture)
);

create table dbo.Tags
(
  Id int identity not null 
    constraint PK_Tags_Id primary key clustered (Id),
  Name nvarchar not null 
);

create table dbo.PostsLocalized_Tags
(
  PostLocalizedId int not null, 
  TagId int not null,
    constraint PK_PostsLocalized_Tags_Post_PostLocalizedId_TagId primary key clustered (PostLocalizedId, TagId)
);
然后,我添加了以下约束:

alter table dbo.PostsLocalized
add constraint FK_PostsLocalized_Id foreign key (Id) references dbo.Posts(Id) on delete cascade on update cascade;

alter table dbo.PostsLocalized_Tags
add constraint FK_PostsLocalized_Tags_PostLocalizedId foreign key (PostLocalizedId) references PostsLocalized(Id) on delete cascade on update cascade,
    constraint FK_PostsLocalized_Tags_TagId foreign key (TagId) references Tags(Id) on delete cascade on update cascade;
但我得到了以下错误:

There are no primary or candidate keys in the referenced table 'PostsLocalized' that match the referencing column list in the foreign key 'FK_PostsLocalized_Tags_PostLocalizedId'.
我怎样才能解决这个问题

谢谢,,
Miguel

您在
PostsLocalized
表上的PK很复杂,由两列组成-
id
culture
,您试图在其中一列上创建FK,这是不可能的


您必须在
PostsLocalized_标记上添加
Culture
列,并在外键中使用它们,或者在
PostsLocalized

上从PK中删除
Culture
,SQL Server要求外键引用必须指向主键或唯一键。外键引用必须指向构成主键/唯一键的所有列。报告说:

在外键引用中,当 保存一个表的主键值的列 被另一个表中的一列或多列引用。本栏 成为第二个表中的外键

外键约束不必仅链接到主键 另一个表中的键约束;它也可以定义为参考 另一个表中唯一约束的列。外键 约束可以包含空值;但是,如果 复合外键约束包含空值,验证 将跳过构成外键约束的所有值。使 确保复合外键约束的所有值均为 已验证,请在所有参与列上指定NOTNULL

PostsLocalized
中的主键包含
culture
列,因此需要将其添加到外键引用中