[英]Issues with creating SQL Server table relationships
I have 2 tables. 我有2张桌子。
First table: 第一表:
create table abc
(
AId INT IDENTITY(1,1),
Name NVARCHAR(50),
EMP NVARCHAR(50)
CONSTRAINT PK_abc PRIMARY KEY (AId, Name)
)
And second table as: 第二张表为:
create table def
(
AId INT,
Comment NVARCHAR(50)
constraint FK_aid FOREIGN KEY (AId) references abc (AId)
)
This throws an error: 这将引发错误:
There are no primary or candidate keys in the referenced table 'abc' that match the referencing column list in the foreign key 'FK_aid'. 在引用表“ abc”中没有与外键“ FK_aid”中的引用列列表匹配的主键或候选键。
So I updated as: 所以我更新为:
create table def
(
AId INT,
Name NVARCHAR(50),
Comment NVARCHAR(50)
constraint FK_AID FOREIGN KEY (AId, Name) references abc (AId, Name)
)
But this throws another error: 但这引发了另一个错误:
More than one key specified in column level FOREIGN KEY constraint, table 'def'. 在列级FOREIGN KEY约束表'def'中指定了多个键。
Not sure what am I missing here. 不知道我在这里想念什么。
---Updated---- - -更新 - -
Sorry for giving vague example. 很抱歉给模糊的例子。 I was having difficulty in explaining my problem here. 我在这里很难解释我的问题。 I have attached the screenshot of my problem. 我已附上我的问题的屏幕截图。 This show the eventual output that I am expecting by making join to 3 tables. 通过连接到3个表,这显示了我期望的最终输出。 Where the data of 3 tables is populated from an input form. 从输入表单填充3个表的数据的位置。
I have tried to provide in a clear way. 我试图以一种清晰的方式提供。 Let me know if you need more inputs. 让我知道您是否需要更多输入。
Attchment at: https://imgur.com/a/jfFS6 出席者: https ://imgur.com/a/jfFS6
Thanks 谢谢
You have an identity column. 您有一个身份列。 Use it as the primary key: 使用它作为主键:
create table abc (
AId INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(50),
EMP NVARCHAR(50)
);
create table def (
AId INT,
Comment NVARCHAR(50)
constraint FK_aid FOREIGN KEY (AId) references abc (AId)
);
Name
should not be in the definition of the primary key. Name
不应该在主键的定义中。
Looks like you have to do it as a separate statement: 看起来您必须作为一个单独的语句来执行此操作:
ALTER TABLE [dbo].[def] WITH CHECK ADD CONSTRAINT [FK_def_abc] FOREIGN KEY([AId], [Name])
REFERENCES [dbo].[abc] ([AId], [Name])
GO
ALTER TABLE [dbo].[def] CHECK CONSTRAINT [FK_def_abc]
GO
But you still should NOT do that. 但你还是应该那样做。 Identity is unique and it alone should be used as primary key. 身份是唯一的,应单独将其用作主键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.