如何在数据库中实现一对多 [英] How to implement ONE-TO-MANY in a database

查看:255
本文介绍了如何在数据库中实现一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中实现一对多概念。
这是场景:我有两个表



(i)。个人(身份证,姓名,年龄,部门)

(ii)。人责任(ID,RESP'S)



一个人可能有多个责任。我应该如何在这里实现一个1-n关系?
其实,我不明白这个正确的概念。



任何建议或链接了解这个 概念,将不胜感激。 解决方案

这个一对多的关系可以像这样用简单的英语来解释...
$ b $ p一个人有一个或多个职责,



AND

每个责任只属于一个人。
$ b $现在根据你正在使用哪个rdbms,你可以实现这个作为外键关系。



首先,您需要添加一列RESPS,指向人员表。



让我们称这个新的列PERSON_ID。

现在我们可以声明关系,代码可能看起来像这样;

  ALTER TABLE [职责]添加CONSTRAINT FOREIGN KEY(PERSON_ID)
REFERENCES [Person](ID)

这个外键约束的声明意味着从现在开始你不能在没有指定拥有这个责任的人的情况下增加一个责任。



<但是你仍然可以添加一个没有任何责任的人(因为没有对人表的限制)。

请注意,这是所有学者,因为在现实生活中,责任是分享的。

换句话说,一个人可能有一个或多个责任,但是每个责任可能属于一个或多个人。



这就是所谓的多一对多的关系,是一个着名的数据库设计问题,一个明确的解决方案 - 我不会进入现在,因为它是切题你的问题。

I want to implement one-to-many concept in my application. This is the scenario: I have two tables

(i). Person(ID, NAME, AGE, DEPT)
(ii). Person Responsibilities(ID, RESP'S)

One person may have more than one responsibility. How shall I implement a 1-n relationship here? Actually, I don't understand the correct concepts for this.

Any suggestions or links to understand this concept would be appreciated.

解决方案

This one-to-many relationship can be interpreted in plain English like this...

A Person has one or more responsibilities,

AND

Each responsibility belongs to exactly one person.

Now depending on which rdbms you're using, you would implement this as a foreign key relationship.

First you need to add a column to RESPS that points to the person table.

Let's call this new column PERSON_ID.

Now we can declare the relationship, the code might look something like this;

ALTER TABLE [Responsibilities] ADD CONSTRAINT FOREIGN KEY (PERSON_ID) 
REFERENCES [Person] (ID)

And this declaration of a foreign key constraint would mean that from now on you cannot add a responsibility without specifying a person who owns that responsibility.

But you could still add a person with no responsibilities (yet) since there are no constraints on the person table.

Note that this is all kind of academic, since in real life responsibilities are shared.

In other words, a person might have one or more responsibilities, but each responsibility might belong to one or more persons.

That's called a many-to-many relationship, and is a well-known database design issue with a well defined solution - which I won't go into now since it's tangential to your question.

这篇关于如何在数据库中实现一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆