SQL Server表创建错误:引用中没有主键或候选键(SQL Server table creation error : There are no primary or candidate keys in the referenced)

一个非常基本的脚本让我发疯。 它说它找不到引用的密钥。 不知道它是什么。 我正在使用SQL SERVER 2014,这个脚本用于创建我的数据库表。 我正在尝试使表id_TABLE_1中的TABLE_2引用表TABLE_1的id。

CREATE TABLE TABLE_1 ( id int identity, email varchar(50) not null, constraint PK_TABLE_1 primary key (id,email) ) GO CREATE TABLE TABLE_2 ( id int identity, id_TABLE_1 int not null, constraint PK_TABLE_2 primary key (id), constraint FK_TABLE_2 foreign key (id_TABLE_1) references TABLE_1(id) on delete cascade ) GO

错误是:

消息1776,16级,状态0,行32 引用表'TABLE_1'中没有主键或候选键与外键'FK_TABLE_2'中的引用列列表匹配。

Msg 1750,Level 16,State 0,Line 32 无法创建约束或索引。 查看以前的错误。

你能帮帮我吗?

A very basic script is driving me crazy. It says it cant find a referenced key. Not idea what it's all about. I'm am using SQL SERVER 2014 and this script is for the creation of my database tables. I'm trying to make the id_TABLE_1 in the table TABLE_2 reference the id of the table TABLE_1.

CREATE TABLE TABLE_1 ( id int identity, email varchar(50) not null, constraint PK_TABLE_1 primary key (id,email) ) GO CREATE TABLE TABLE_2 ( id int identity, id_TABLE_1 int not null, constraint PK_TABLE_2 primary key (id), constraint FK_TABLE_2 foreign key (id_TABLE_1) references TABLE_1(id) on delete cascade ) GO

The error is :

Msg 1776, Level 16, State 0, Line 32 There are no primary or candidate keys in the referenced table 'TABLE_1' that match the referencing column list in the foreign key 'FK_TABLE_2'.

Msg 1750, Level 16, State 0, Line 32 Could not create constraint or index. See previous errors.

Can you help me here ?

最满意答案

根据评论,您试图引用不存在的索引。 TABLE_1表上的主键是一个包含两列的复合键: id和email 。

要进行编译,您可以将主键更改为:

CONSTRAINT PK_TABLE_1 PRIMARY KEY (id)

或者只在id列上创建一个新索引:

CREATE INDEX IX_TABLE_1_id ON TABLE_1 (id);

As per comment, you are trying to reference an index that doesn't exist. The primary key on your TABLE_1 table is a composite key containing two columns: id and email.

For this to compile, you can either alter your primary key to:

CONSTRAINT PK_TABLE_1 PRIMARY KEY (id)

or create a new index on just the id column:

CREATE INDEX IX_TABLE_1_id ON TABLE_1 (id);

更多推荐