Difference between one-to-many and many-to-one relationship
Asked Answered
R

15

166

What is the real difference between one-to-many and many-to-one relationship? It is only reversed, kind of?

I can't find any 'good-and-easy-to-understand' tutorial about this topic other than this one: SQL for Beginners: Part 3 - Database Relationships

Roslynrosmarin answered 5/1, 2011 at 7:23 Comment(2)
This is perfect explanation: en.wikipedia.org/wiki/Many-to-many_(data_model)Namely
@Namely how is the many-to-many article relevant to the question? You probably rather meant en.wikipedia.org/wiki/One-to-many_(data_model)Harkins
C
149

Yes, it is vice versa. It depends on which side of the relationship the entity is present on.

For example, if one department can employ several employees then department to employee is a one-to-many relationship (1 department employs many employees), while employee to department relationship is many-to-one (many employees work in one department).

More info on the relationship types:

Database Relationships - IBM DB2 documentation

Calvities answered 5/1, 2011 at 7:30 Comment(4)
I am afraid that doesn't make scenes! (NOT SURE BUT) i think the order represents dependency! Doesn't it?? E.G, A User to Role may be 1 to many but not many to one because one cannot get references of the user that use the role! Does that make sense?Ljubljana
Maybe database relationships now?Dedededen
But What if one employee can work in only one department? huh? There is no such Many to One.Acquittance
That is correct but I believe it needs some further explanation, justification in technical terms. Developer has to understand the difference of RDBMS with ORMs and Object-Relational DBMS. See my answer.Platinumblond
Q
41

From this page about Database Terminology

Most relations between tables are one-to-many.

Example:

  • One area can be the habitat of many readers.
  • One reader can have many subscriptions.
  • One newspaper can have many subscriptions.

A Many to One relation is the same as one-to-many, but from a different viewpoint.

  • Many readers live in one area.
  • Many subscriptions can be of one and the same reader.
  • Many subscriptions are for one and the same newspaper.
Q answered 5/1, 2011 at 7:26 Comment(0)
C
30

What is the real difference between one-to-many and many-to-one relationship?

There are conceptual differences between these terms that should help you visualize the data and also possible differences in the generated schema that should be fully understood. Mostly the difference is one of perspective though.

In a one-to-many relationship, the local table has one row that may be associated with many rows in another table. In the example from SQL for beginners, one Customer may be associated to many Orders.

In the opposite many-to-one relationship, the local table may have many rows that are associated with one row in another table. In our example, many Orders may be associated to one Customer. This conceptual difference is important for mental representation.

In addition, the schema which supports the relationship may be represented differently in the Customer and Order tables. For example, if the customer has columns id and name:

id,name
1,Bill Smith
2,Jim Kenshaw

Then for a Order to be associated with a Customer, many SQL implementations add to the Order table a column which stores the id of the associated Customer (in this schema customer_id:

id,date,amount,customer_id
10,20160620,12.34,1
11,20160620,7.58,1
12,20160621,158.01,2

In the above data rows, if we look at the customer_id id column, we see that Bill Smith (customer-id #1) has 2 orders associated with him: one for $12.34 and one for $7.58. Jim Kenshaw (customer-id #2) has only 1 order for $158.01.

What is important to realize is that typically the one-to-many relationship doesn't actually add any columns to the table that is the "one". The Customer has no extra columns which describe the relationship with Order. In fact the Customer might also have a one-to-many relationship with ShippingAddress and SalesCall tables and yet have no additional columns added to the Customer table.

However, for a many-to-one relationship to be described, often an id column is added to the "many" table which is a foreign-key to the "one" table -- in this case a customer_id column is added to the Order. To associated order #10 for $12.34 to Bill Smith, we assign the customer_id column to Bill Smith's id 1.

However, it is also possible for there to be another table that describes the Customer and Order relationship, so that no additional fields need to be added to the Order table. Instead of adding a customer_id field to the Order table, there could be Customer_Order table that contains keys for both the Customer and Order.

customer_id,order_id
1,10
1,11
2,12

In this case, the one-to-many and many-to-one is all conceptual since there are no schema changes between them. Which mechanism depends on your schema and SQL implementation.

Hope this helps.

Cioban answered 21/6, 2016 at 20:45 Comment(10)
The general case is called an inclusion dependency. A foreign key constraint is the most common type of inclusion dependency but not all inclusion dependencies involve a foreign key. The common attribute or attributes (the "reference") always exist in both tables. On the "one" side those attributes are called a candidate key. On the "many" side they may be a foreign key. The terms "one-to-many" or "many-to-one" could be applied to any inclusion dependency that involves at least one candidate key without necessarily implying which side may be optional.Chameleon
Interesting @sqlvogel. In Java the javax.persistence.OneToMany differently than the ManyToOne. Are you saying that they are synonymous or just that it depends on the implementation? Is my answer incorrect?Cioban
The question is about relational databases and SQL, not Java. Maybe you are right about Java.Chameleon
I was using it as an example @sqlvogel. Are you saying that "one-to-many" and "many-to-one" are synonymous?Cioban
I'm saying that those are two ways of describing exactly the same relationship but from different perspectives. In the same way that "A is a subset of B" means the same as "B is a superset of A".Chameleon
Gray, the last two paragraphs read the same to me. How do you implement a many-to-one? I thought you said it adds columns to the one side...Carhart
I've tweaked my answer @AlexanderSuraphel. The id column is often added to the many table. The id references (points-to) the one table.Cioban
Gray, I don't know if I am missing something obvious but what I am reading from BOTH cases is that there is no column added to the one side. What is the difference then?Carhart
That's right @AlexanderSuraphel. So on the difference is that on the Account side it has @OneToMany and on the Order side it has @ManyToOne which adds the accountId to the Order entity. Again, the difference is conceptional.Cioban
For me, this is a straight explanation just one thing it will complete if you can include some example about how to create a table with these two relations.Spot
V
14

SQL

Two tables with one relation

In SQL, there is only one kind of relationship, it is called a Reference. (Your front end may do helpful or confusing things [such as in some of the Answers], but that is a different story.)

  • A Foreign Key in one table (the referencing table)
    References
    a Primary Key in another table (the referenced table)

  • In SQL terms, Bar references Foo
    Not the other way around

    CREATE TABLE Foo (
        Foo   CHAR(10)  NOT NULL, -- primary key
        Name  CHAR(30)  NOT NULL
        CONSTRAINT PK             -- constraint name
            PRIMARY KEY (Foo)     -- pk
        )  
    CREATE TABLE Bar (
        Bar   CHAR(10)  NOT NULL, -- primary key
        Foo   CHAR(10)  NOT NULL, -- foreign key to Foo
        Name  CHAR(30)  NOT NULL
        CONSTRAINT PK                -- constraint name
            PRIMARY KEY (Bar),       -- pk
        CONSTRAINT Foo_HasMany_Bars  -- constraint name
            FOREIGN KEY   (Foo)      -- fk in (this) referencing table
            REFERENCES Foo(Foo)      -- pk in referenced table
        )
    
  • Since Foo.Foo is a Primary Key, it is unique, there is only one row for any given value of Foo

  • Since Bar.Foo is a Reference, a Foreign Key, and there is no unique index on it, there can be many rows for any given value of Foo

  • Therefore the relation Foo::Bar is one-to-many

  • Now you can perceive (look at) the relation the other way around, Bar::Foo is many-to-one

    • But do not let that confuse you: for any one Bar row, there is just one Foo row that it References
  • In SQL, that is all we have. That is all that is necessary.

What is the real difference between one to many and many to one relationship?

There is only one relation, therefore there is no difference. Perception (from one "end" or the other "end") or reading it backwards, does not change the relation.

Cardinality

Cardinality is declared first in the data model, which means Logical and Physical (the intent), and then in the implementation (the intent realised).

Cardinality

One to zero-to-many
In SQL that (the above) is all that is required.

One to one-to-many
You need a Transaction to enforce the one in the Referencing table.

One to zero-to-one
You need in Bar:

CONSTRAINT AK    -- constraint name
    UNIQUE (Foo) -- unique column, which makes it an Alternate Key

One to one
You need a Transaction to enforce the one in the Referencing table.

Many-to-Many

There is no such thing at the Physical level (recall, there is only one type of relation in SQL).

At the early Logical levels during the modelling exercise, it is convenient to draw such a relation. Before the model gets close to implementation, it had better be elevated to using only things that can exist. Such a relation is resolved by implementing an Associative Table at the physical [DDL] level.

Many-to-many Resolved

V1 answered 17/2, 2019 at 11:0 Comment(2)
@Martijn Peters. I can edit it to comply with the code of conduct. But you have also removed (a) explanation, and (b) evidenced facts in reality. What do I do about those ?V1
Find a different way to express those things without resorting to ranting, name calling, and casting aspersions on anyone’s intellect or professional conduct. Focus on the tech, not on the people that may or not be wrong.Benia
C
6

There is no difference. It's just a matter of language and preference as to which way round you state the relationship.

Chameleon answered 5/1, 2011 at 11:37 Comment(2)
There certainly is a difference, both conceptually as well as the generated schema. See my answer: https://mcmap.net/q/149082/-difference-between-one-to-many-and-many-to-one-relationshipCioban
@Gray. No there is not. Your answer is not only incorrect, it confuses beginners (the ones asking this question).V1
S
5

One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).

The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:

  1. Multiplicity (ER term: cardinality)
  • One-to-one relationships (abbreviated 1:1): Example Husband and Wife
  • One-to-Many relationships (abbreviated 1:N): Example Mother and Children
  • Many-to-Many relationships (abbreviated M:N): Example Student and Subject
  1. Directionality : Not affect on mapping but makes difference on how we can access data.
  • Uni-directional relationships: A relationship field or property that refers to the other entity.
  • Bi-directional relationships: Each entity has a relationship field or property that refers to the other entity.
Steenbok answered 3/9, 2017 at 10:20 Comment(4)
There is no "directionality" in a relational database. Each relationship has two "ends": the Reference (table being referenced) and the Referencing (table doing the referencing). SQL/DML allows any table to be referenced, any way you want … one side … the other side … both sides … no sides.V1
@PerformaceDBA - If the relation has a foreign key constraint, then there is directionality,Mercado
@Mercado 1) In SQL DDL, to establish a relationship, a FOREIGN KEY Constraint has to be specified. Therefore all relationship are FK Constraints. 2) That is at the physical DDL level, ignoring the logical (which is the question). The Relational Model is logical. When viewed logically, when coding SQL DML, the relationship has two "ends", it is not limited to whatever the DDL declares.V1
for more relationaldbdesign.com/database-design/module6/…Steenbok
S
4

Answer to your first question is : both are similar,

Answer to your second question is: one-to-many --> a MAN(MAN table) may have more than one wife(WOMEN table) many-to-one --> more than one women have married one MAN.

Now if you want to relate this relation with two tables MAN and WOMEN, one MAN table row may have many relations with rows in the WOMEN table. hope it clear.

Synaesthesia answered 23/11, 2012 at 3:32 Comment(1)
Downvoted, you should come up with an example more appropriate than polygynyImpuissant
P
2

This is an excellent question, according to my experience, in ERD diagrams and relational databases direction is implied. In RDBMS you always define Many-To->One (trivial case One-To->One) relationships. The Many side of the relationship, a.k.a children, references the One side, a.k.a parent and you implement this with a Foreign Key constraint. Technically speaking you have to access an index, fetch the Primary Key record of the One side and then visit this record to get more information.

You cannot do this the other way around unless we are speaking about Object-Relational DBMS such as Postgres, Intersystems Cache, etc. These DBMS allow you to define a bi-directional relationship between the two entities (tables). In that case accessing records the other way around, i.e. One--To-->Many is achieved by using an array of references (children). In ORMs you have classes that reference each other the same way we described here.

WARNING: Most RDBMS in the IT market are NOT relational database management systems in the strict sense, think about null values, duplicate records etc, many of these allowed features break the definition of what a Relation is.

Platinumblond answered 16/4, 2021 at 12:1 Comment(1)
The commercial RDBMS SQL Platforms (except Oracle) are Relational. The freeware is not Relational (allows prohibited objects such as Circular References), and not SQL compliant.V1
Z
0

There's no practical difference. Just use the relationship which makes the most sense given the way you see your problem as Devendra illustrated.

Zeb answered 7/8, 2013 at 8:37 Comment(1)
@Gray. No there is not. Your answer is not only incorrect, it confuses beginners (the ones asking this question).V1
V
0
  • ---One to Many--- A Parent can have two or more children.

  • ---Many to one--- Those 3 children can have a single Parent

    Both are similar. This can be used according to the need. If you want to find children for a particular parent, then you can go with One-To-Many. Or else, want to find parents for twins, you may go with Many-To-One.

Vein answered 1/2, 2018 at 10:0 Comment(0)
M
0

One-to-many and Many-to-one relationship is talking about the same logical relationship, eg an Owner may have many Homes, but a Home can only have one Owner.

So in this example Owner is the One, and Homes are the Many. Each Home always has an owner_id (eg the Foreign Key) as an extra column.

The difference in implementation between these two, is which table defines the relationship. In One-to-Many, the Owner is where the relationship is defined. Eg, owner1.homes lists all the homes with owner1's owner_id In Many-to-One, the Home is where the relationship is defined. Eg, home1.owner lists owner1's owner_id.

I dont actually know in what instance you would implement the many-to-one arrangement, because it seems a bit redundant as you already know the owner_id. Perhaps its related to cleanness of deletions and changes.

Mincing answered 15/10, 2020 at 21:36 Comment(0)
E
0

The easiest explanation I can give for this relationship is by piggybacking on evendra D. Chavan'sanswer.

Using the department and employee relationship

A department can have multiple employees, so from the employee side, it's one-to-many relationship, and from the department side it's many-to-one relationship

But if an employee can also belong to more than one department, we can also say from the employee side it's now many as opposed to one, so the relationship becomes many-to-many

In order words, a simple understanding would be, we can state that a relationship is many-to-many if one-to-many can be viewed from both sides that is if;

  • one employee can belong to many departments (one-to-many)
  • one department can have many employees (one-to-many)
Edelstein answered 13/6, 2021 at 6:23 Comment(0)
E
0

I am new to SQL and only have experience using SQLAlchemy. The documentation on relationships in SQLAlchemy does a good job explaining this, in my opinion.

You may find some clarity by reading this part

Also, I had to come up with my own example to think through this. I'll try to explain without writing a bunch of code for simplicity.

table Vehicle

  • column (name)

table Manufacturer

  • column (name)

A Vehicle can only have One manufacturer (Ford, Tesla, BMW etc.)

Manufacturers can make many Vehicles

Ford

  • Ford makes Mustang
  • Ford makes F-150
  • Ford makes Focus Tesla
  • Tesla makes Model S
  • Tesla makes Model X
  • Tesla makes Roadster

When looking at the database rows you will want to decide if you want a column that references the other side of the relationship. This is where the SQLAlchemy documentation brings in the difference between backref vs. back_populates. I understand that is the difference between having a column in the table to reference the other side of the relationship or not having a column to reference the other side.

I hope this helps, and even more so, I hope I am accurate in the way I learned and understand this.

Einsteinium answered 4/4, 2022 at 16:39 Comment(0)
E
0

I have read most of the answer. The problem is not the relationship here at all. If you look at One to Many or Many to One conceptually, it is just a reversible relationship. HOWEVER, while implementing the concept in your software or application it differs a lot.

In case of Many to One, we often desire the table that has Many aspect to be written first and we desire it to associate with the table containing One aspect. If you convert Many to One concept into One to Many, you will have hard time writing the One aspect table first in your code. Since, the relationship is defined while you engineer the database, Many aspect table will seek for the One aspect table data for integrity. So if you are planning to do it by using foreign key -> unique key or foreign key -> primary key, Many to One implementation will be different even if you consider it as a One to Many.

I personally make associations without using actual relationship concepts in many cases. There is no such boundaries as to use Database concept to form relationship every time. Just make sure that your database integrity is maintained as you want, it is indexed properly for your search needs and is decently normalized.

Electrotechnics answered 6/5, 2022 at 7:55 Comment(0)
H
-6

one-to-many has parent class contains n number of childrens so it is a collection mapping.

many-to-one has n number of childrens contains one parent so it is a object mapping

Hyaloplasm answered 7/1, 2013 at 12:30 Comment(3)
this answer is good and have additional information don't understand why it was down voted, in unidirectional context one to many and many to one will not provide the same code quality depending on the UX: If you need to get a set of data related so one to many is wiser were you dont need a select statement where some condition is fine because the set is there in the map, however if the user doesn't need to get the set of data and is interested of each row as a unique desired instance so Many to one is wiser choiceMcclimans
It may be a good answer, but they are not the same: many-to-one has a parent class containing n number of children, one-to-many has many parent's to one child. In SQL it may not make a difference as the many-to-one relationship can be omni-directional but in a framework such as Django, this is a major issue, as there is no one-to-many relationship and the foreign key which deals with the Many-to-One relationship only works naturally in one direction, this cannot be used the other way round in the same way.Hobo
What @MohammedHousseynTaleb writes is true for Object-Relational DBMS and ORMs see my answer for justification. It is not fair downgrading him without properly justifying your action.Platinumblond

© 2022 - 2024 — McMap. All rights reserved.