在sql server express中使用键和约束

发布于 2024-10-26 08:23:33 字数 291 浏览 2 评论 0原文

我有 2 个表:

**FamilyHeads**
HeadID   | HeadName      


**FamilyMembers**
MemberID  |  MemberName      

现在,我希望如果存在族长,则只有家庭成员可以插入 FamilyMembers 表中。为此,我是否应该将 HeadID 列也包含在 FamilyMembers 表中并从 FamilyHeads 表中引用它。或者这个问题的解决方案是什么。我知道我必须使用主键和外键,但不确定实施情况。请帮忙看一下代码。

I have 2 tables :

**FamilyHeads**
HeadID   | HeadName      


**FamilyMembers**
MemberID  |  MemberName      

Now, i want that if a family head exists , then only family members could be inserted in the FamilyMembers table. For this, should i include the HeadID column also in my FamilyMembers table and reference it from the FamilyHeads table. or what's the solution for this. I know that i have to use Primary and Foreign keys but not sure with the implementation. Please help with the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猥琐帝 2024-11-02 08:23:33

添加主键

ALTER TABLE FamilyHeads WITH CHECK ADD
     CONSTRAINT PK_FamilyHeads PRIMARY KEY CLUSTERED (HeadID)
GO
ALTER TABLE FamilyMembers WITH CHECK ADD
     CONSTRAINT PK_FamilyMembers PRIMARY KEY CLUSTERED (MemberID)
GO

添加外键列

--Same datatype, NOT NULL!
ALTER TABLE FamilyMembers ADD
    HeadID int NOT NULL
GO

添加 FK

ALTER TABLE FamilyMembers WITH CHECK ADD
     CONSTRAINT FK_FamilyMembers_FamilyHeads FOREIGN KEY (HeadID)
            REFERENCES FamilyHeads (HeadID)
GO

您是否可以有重复的 HeadName?如果否

ALTER TABLE FamilyHeads WITH CHECK ADD
     CONSTRAINT UQ_FamilyHeads_HeadName UNIQUE (HeadName)
GO

如果是,您如何知道将哪些成员添加到哪个头?

并在 HeadID 上为 FamilyMembers 添加非唯一索引

Add primary keys

ALTER TABLE FamilyHeads WITH CHECK ADD
     CONSTRAINT PK_FamilyHeads PRIMARY KEY CLUSTERED (HeadID)
GO
ALTER TABLE FamilyMembers WITH CHECK ADD
     CONSTRAINT PK_FamilyMembers PRIMARY KEY CLUSTERED (MemberID)
GO

Add columns for foreign key

--Same datatype, NOT NULL!
ALTER TABLE FamilyMembers ADD
    HeadID int NOT NULL
GO

Add FK

ALTER TABLE FamilyMembers WITH CHECK ADD
     CONSTRAINT FK_FamilyMembers_FamilyHeads FOREIGN KEY (HeadID)
            REFERENCES FamilyHeads (HeadID)
GO

Can you have duplicate HeadNames? if no

ALTER TABLE FamilyHeads WITH CHECK ADD
     CONSTRAINT UQ_FamilyHeads_HeadName UNIQUE (HeadName)
GO

If yes, how will you know which members to add to which head?

And add an non-unique index to FamilyMembers on HeadID

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文