What are Parent-Child relationships? - sql

What is the parent and what is the child in a sql relationship?
In my case, I have a part (Say screw), and product material. For argument's sake, a product material (eg steel) can only belong to one part (but not in the real world). So this is 1:n. The part will have its pk as a fk in the ProductMaterial table.
Which is parent and which is child in this case?

Relational databases such as SQL actually have no concept of parent/child relationships - that is an interpretation that you as a programmer put on the data. There are architectures that explicitly state and use such relationships, such as heirarchical (and to a certain extent OO) databases.

You can interpret a 1:n relationship in database this way: A child is always that model which holds the foreign key as this indicates where it belongs to.
Of course if you have self referencing models/tables you have to look at it in a different way.

In this case, Part is parent and ProductMaterial is child.
A parent can have unlimited numbers of children (scary thought - 2 is enough for me!), whereas a child can have only a limited number of parents - and in DB terms, only 1!

Usually in a one-to-many relationship, it's the "one" record that is the parent, and the "many" records that are the children.
Of course, in some cases it doesn't make any sense to talk about a parent-child relationship. In your example it makes some kind of sense at least. In other examples you may even find the opposite, where a child has many parents, but then it's not very useful to describe it that way.

Another way to look at this, in addition to what David M. said, is in terms of an ORM implementation (such as Linq to SQL). You have two entities, Part and ProductMaterial. Each part entity has a set of ProductMaterial entities (children entities or an EntitySet). Each ProductMaterial entity has zero or one Part entity (parent entity or an EntityRef).
Randy

I would say that any table which has a one to many relationship with one or more other tables can be considered a parent to those other tables. Self joining? An ambiguous term which I don't think anyone understands.

'Product' is parent and 'Product material' is child in Product_ProductMaterial relationship or association.
If you delete a child, parent can live and continue life. If you delete parent, child become orphan or identityless which is not good. If A can not not be deleted before B is deleted, then A is parent and B is child.
If I guess right, in your case in Product_ProductMaterial relationship, if you delete Product, ProductMaterial will be assigned to no one, become orphan, identity crisis. But if you delete ProductMaterial, Product can still be there, no need identity support.
Sorry if my wordings are not good.

Related

Need to convert SQL Query to Coredata Format

SQL Query
select * from zchildren where zparent = 3586 OR zparent in (Select zid from zchildren where zparent = 3586)
I have tried few cases with $SUBQUERY but Still i am not getting any success. So how can i achieve this ?
Update
I have Table Name which is Children which has Parent which contains the ID of the same table ID , Its a Inverse Relationship now i want All the children which parent is '3586' and its all sub children
Update2
I am Attaching the screen shot
Now Few more points
Table Group has One-To-Many Relationship with Children
Table Children has Two Relationship
First which is Inverse to Group One-To-One
Second children relation which is Inverse to itself which is called Reflexive
Updated Question
Now suppose i have one Query i want to search from Children table where title is 'Medical' AND Parent is '3586'
Now This '3586' is parent id which is coming from Table Group And i can easily predicate this .
Problem
It Gives me children whose parent '3586' but i also want to search in the title of sub-children which are Reflexive of this parent ID , Means sub-children of children which came from parent '3586'.
I really need this solution. I can still update my question if any one is not clear in this question.
When tackling somewhat complicated Core Data issues, you really have to be a bit more accurate. Your code and your variable names are sloppy and wrought with mistakes.
In your SQL query you have an attribute parent (or "zparent"), but in the Core Data model it becomes an attribute rather than a relationship. (Were you perhaps thinking of modeling ids? That would indicate that you are still trapped in relational database thinking and have not fully grasped the concept of the object graph yet. Forget about ids and think in relationships instead.)
You need a reverse relationship to children, so this cannot be the same relationship. Calling the entity "Children" is confusing because 1) you are using the plural for a singular object and 2) you are calling both parent and children "Children". You also misspell "Children" as "Childran", potentially leading to all sorts of errors.
Instead, let me suggest the entity name Person. A person can have one or more parents (or is it only one?) and one or more children both of which are also of type Person, resulting in a many-to-many relationship:
Person - parents <<----------------->> children - Person
If a person can only have one parent it if of course a many-to-one relationship.
Person - parent <------------------->> children - Person
You can then fetch a Person with idNumber 3586 (notice that using id is perhaps also a bad idea as it is a reserved word in some contexts). You can then access that person's children very succinctly:
person.children
That's really all there is to it.

Are non-identifying OneToMany relationship automatically ManyToMany relationships?

I just read this: What's the difference between identifying and non-identifying relationships?
And the example for a non-identifying relationship there sounds like it should be a many to many table. One person can have multiple states and one state can be used by many persons.
And I can't really think of an example where a non-identifying relationship should not be a ManyToMany relationship.
So, can someone elaborate on this? Because I can't come up with any examples that go against this.
EDIT:
For example, an identifying relationship would be an appletree having apples. Those apples got spawned because of the appletree. So the appletree has many apples but each apple belongs only to that one tree.
A non-identifying OneToMany relationship would then have to have something that spawned independently, but can only ever belong to one other thing. Because if it belongs to multiple things that themselves have multiple instances...
Hang on I just realized the case where the instance A can have only one instance of B but one B can be linked to multiple A's, while B got created independently.
Case closed I guess.
non-identifying OneToMany relationship, is a OneToMany relationship.
On the other side:
A identifying OneToMany relationship could be inverted into a OneToOne relationship.
Example:
Person X has phonenumber 123456. Although in the table "Phones" many phonenumbers are present, phonenumber 123456 is probably only present once. So this phonenumber identifies person X.
Although Person X can have multiple phones, the "Many" side is almost a unique identifier and thus a sort of "one-to-one" relationship.
Example of Non-identifying:
Person X lives in Canada. If you search on Canada, you will find many persons (probably). But if you revert this query, a lookup on Canada, it's not a manytomany, but a onetomany relationship.

One-to-one mapping confusion

Why is it that a lot of people are referring to One-to-One when I am sure they are referring to Many-to-one?
For instance, if you have two tables;
Inventory (InventoryID)
Item (ItemID, InventoryFK)
There is no one-to-one mapping here as far as I can tell. It's "Many items to one inventory".
Now, let's assume that there would be only one item per inventory. In this case, my colleagues would start calling it a "one-to-one". Am I correct in pointing out that it's still a many-to-one relationship? When I try to explain this to them they don't seem to understand.
I believe a proper one-to-one mapping to be something like this:
Person (Column: PersonID, Name)
PersonAddress (Column: PersonID, StreetName, StreetNumber)
Here you'd have two tables, sharing the exact same PK.
Assuming my assumptions are correct, why are so many people abusing the term "one-to-one"?
The one-to-many and one-to-one relation are implemented in a slightly different way.
One-to-many
Object (objectId) ObjectCharacteristics(charId,objectId)
One-to-one
The order of the table is not important:
Husband (husbandId) Wife(wifeId,husbandId) + unique constraint on husbandId
N.B. One-to-many relation is also a one-to-one relation in the order way. The ObjectCharacteristics has one and only one object.
But you are right the relationship is a concept that does not depend upon the specific data in your database but only on the structure of it.
I agree these terms are much abused. But who of us isn't guilty? Without knowing the constraints involved, your example of what you believe to be a one-to-one relationship could be a one-to-zero-or-one relationship (hint: the presence of a foreign key does not imply the presence of actual referencing values).
Chris Date wrote a very thorough analysis of the situation in his paper All for One, One for All.

Difference between one-to-many and many-to-one relationship

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
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
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.
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.
SQL
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).
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.
There is no difference. It's just a matter of language and preference as to which way round you state the relationship.
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.
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:
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
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.
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.
There's no practical difference. Just use the relationship which makes the most sense given the way you see your problem as Devendra illustrated.
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.
---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.
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)
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.
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.
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

SQL database design

I am making a database for a program where i am supposed to model some relations in the family.
ex:
X is father to Y , Y is son to X
So , i have a Members table with all info about each member so i thought about making a many to many relation between the Members table and itself so that the Member_Member bridge table will be having the columns "FK_FromID , FK_ToID" as composite key (is this correct ?) and "FK_RelationType" as a foreign key to RelationTypes table which will have the relation type "Father,mother, son,daughter" , and two relations going as one to many from the Members table to these two foreign keys
My problem is : when deleting if i choose cascading then i will make cycles because if i delete a member then there will be two delete passes to related records in Member_Member bridge , knowing that in the program whenever i insert a father relation i will insert a son relation as well in the Member_Member table , is there a way or a workaround possible to enable cascading so that whenever i delete a member i will delete the related records in Member_member regardless of being recorded in either a to or a from foreign key column
So, i don't know what to do , is this a correct design in the first place or what ? , what should i do about cycling , also what do you think a better design for the same problem should be knowing that i need to specify what kind of relation between the two parties
Thanks a lot for any help , and sorry for bad english
Bishoy
SQL does not handle "network" problems like this very well.
The member-member bridge table is a terrible name. It's a "member-parent" (or "parent-child") bridge. Bridge tables should not have a "composite key". Bridge tables have a surrogate key (just a sequential number) and a pair of FK references to other tables. The two FK's should have names like "member" and "parent" to make it perfectly clear what the relationship is in this table.
Everyone has a parent. Not everyone has children. Some parents will not have parents in this database; they're the "top parents".
It's easiest if the top parents have rows in the parent-child bridge with a parent FK of NULL. That way you avoid super-complex outer-joins -- every member has at least one member-parent row; ideally two.
You will find many "cycling" issues since relationships are transitive.
Note that you can't -- in a single standard SQL query -- find all members of the family, or all parents back to the top of the family, or all children and grand-children. There are SQL extensions that make this possible, but the standard doesn't handle it well.
The cascading delete doesn't work out well because the relationships in a family are directed in two ways (parent to children, child to parents), but SQL only has one kind of direction (FK reference).
You can try to assure that every member MUST have at least one (and at most two) rows in "member-parent" and the delete of a member deletes the two rows in "member-parent" and the keys have the proper names, you might make parts of this work.
Note that when you delete a member, this will break their parent relationships. You delete the member-parent row. That's good. What about their children? The other rows which have member-parent referring to this deleted parent are now broken. What does this mean? What should be done?
There's no standard answer. Removing rows from a connected graph leaves elements
unconnected. You have to work out some sensible rules for that.
Since SQL does not do this well, all designs will seem to have problems.
Assuming each member can only have one mother and one father, you would be able to derive all the relationships by simply keeping a mother_id and father_id field in the members table.
However this would only work if your database will not have missing information. For example, if member X is the brother of member Y, there would be no way to know this unless the parents of X and Y are stored in the database.
If your database will not be having missing information, the above might be easier to manage data integrity. Queries might get a bit complex however.
The member_member bridge you suggested has one serious problem since it implies a direction of the relationship, so that if X is the father of Y, Y is also the son of X. You suggested to define the relationship twice in both directions, but in general this is not recommended. This is a form of data duplication, and you can struggle to enforce referential integrity with duplication of data. Remember that the DBMS does not know that X is father of Y is the same as Y is the son of X.
I am aware that this is not a complete answer, but just a few observations. I totally agree with S.Lott's answer as in there is no standard way to "solve" this with relational databases.