Database how to model 1:1 relationship - sql

(VS2008, SqlCE 3.5)
I try to model a 1:1 relationship. So I put the foreign key in the parent table, holding the PK of the child table. Then I set the foreign key to UNIQUE. Still when I create my entity classes (With SqlMetal), the child class has a reference to an EntitySet of the parent, not just a single entity. This seems like a m:1 relation? So what I need to do to make it 1:1 ?
EDIT1:
I'm confused.. Trying to make a set, like this:
StrategySet(ID, EntryStrategyID{Unique}, ExitStrategyID{Unique})
EntryStrategy(ID)
ExitStrategy(ID)
Is this m:1 isn't it? Though it looks like FK's are in the parent, or wouldn't we name StrategySet the parent? And how would I now change this too 1:1 ?

First of all, the parent is table which is referenced by FK from child. So you can't say that your parent table references the child: it's not correct.
Secondly, 1:1 relations can be made through:
Primary Keys in both tables
Primary Key in parent and Unique Foreign Key in child
So in your case, the architecture is correct. I suppose you should check the structure again, and look through this article.

If all columns in EntryStrategy and ExitStrategy are the same, then all you need is simply this (add all other columns too).
If EntryStrategy and ExitStrategy have some different columns, then use this. Keep all common columns in the Strategy table. EntryStrategy and ExitStrategy have only columns specific to each one.
Here is also a generic example of 1:1 due to vertical partitioning of a table.
Before:
After:

Let me understand the situation you are describing.
You have set of fields which make up a "Strategy". A subset of the fields are conceptually the "EntryStrategy" and a non-intersecting subset of the fields are the "ExitStrategy".
In your case a given set of values making up an "EntryStrategy" can be joined with one and only one set of values making up an "ExitStrategy". This is what you mean when you say there is a 1:1 correspondence.
As smirkingman said earlier, in classic relational database modeling, all of these fields belong in a single table because no subset of the fields appear in more than one record.
If you could have multiple ExitStrategies for a single EntryStrategy then you would have two tables with the EntryStrategy being the parent and the ExitStrategies being the children and the ExitStrategy records would have a Foreign Key pointing to the EntryStrategy parent record.
If you could have multiple EntryStrategies for a single ExitStrategy then you would have two tables with the ExitStrategy being the parent and the EntryStrategies being the children and the EntryStrategy records would have a Foreign Key pointing to the ExitStrategy parent record.
If you could have multiple EntryStrategies associated with multiple ExitStrategies then you would have a many-to-many relationship which requires a third table to maintain the correspondences.
The principles of classic database modeling would put all your fields in one table.
As St Woland wrote, you can enforce the 1:1 relationship by having two tables where the foreign key in the child table is a Unique index. But two tables are normally used for 1-to-many relationships.
As Damir wrote, you can enforce the 1:1 relationship by having three tables where the third table has a foreign key to each of the other two tables and both foreign key fields are marked as Unique indices. However, normally you only use three tables in this fashion when you have a many-to-many relationship.
I think you are expecting way too much from the automated data modeling tools to expect them to construct entities that represent your very unconventional approach.
The answer to your main question is simple. How do I represent a 1:1 relationship? You put them in the same record in a single table!

Related

Mapping a 1:1 relationship on a relational schema

If I have two entities and the relation between them is 1:1. Also the participation of each of them is total... What I should do in this case in order to represent the relationship between them in the relational schema?
If the 1:1 relationship with total participation is the only relationship between the two entities, you just merge them into a single relation. The choice of the primary key will be arbitrary (pick one of the PK of the original entities, while the other PK will be an alternate key).
If instead there are additional relationships between the two entities, which prevent the merge into a single relation, you can treat the entities as in a parent-child relationship, and the choice of where to put the foreign key is arbitrary.
In the relational model that's called a join depencency and it can be simply expressed as a constraint between two relations such that P(A) = P(B), where P(A) and P(B) are projections on relations A and B. Although it's easy to support in relational terms, unfortunately SQL makes it difficult or impossible to enforce join dependencies between different tables because standard SQL doesn't support the ability to update more than one table simultaneously. To implement in SQL you have to either combine them into one table or temporarily disable the constraint while the tables are updated.

Insertion when both sides are mandatory in entity relationship

I am preparing for an exam from databases and there is this one thing that puzzles me. From what I've read both sides of any relationship can be constrained to be NOT NULL. I've seen it in at least 2 books and various articles.
Nobody however explains how to insert values into these tables. As far as I know it is not possible in most databases (with the exception of Oracle) to insert into multiple tables at once. That means that it would be needed to insert into one of the tables first. However at that moment there doesn't exist a corresponding entry in the second table so I cannot reference it which violates the NOT NULL constraint.
Another problem is that it is hard to enforce the relationship from both sides in 1:N or M:N relationship. (I can only think of triggers)
So the question is: Are these relationships really implementable or are they just "theoretical" concept which is not used in real life?
To implement a relationship between two entities (tables) in SQL, the primary key of a table (Table1) is make the foreign key in the other table (Table2). If it’s two way mandatory relationship (NOT NULL for both tables) then the entries should be first inserted in Table1 which has the primary key first and then the entries for the other Table2 containing the primary key of the Table1 as the foreign key should be inserted. Check this link for more details and an example.

Is it fine to have multiple foreign keys from one table to single primary key in another table?

Say I have two tables
Products table:
|ProductID|ProductName|ListPrice|
PrebuiltSystems table:
|BuldID|Processor|Motherboard|RAM|
The values for the Processor, Motherboard etc. are all existing ProductID's. I am now creating
foreign key relationships from each of the part name columns to the one ProductID and have a bunch of navigation properties and relationships lines being created for each part. Is this ok?
Or is there some kind of relationship merger/rule that I can use to say all those columns are foreign keys to productID without creating one to one relationships ?
Is this ok?
Yes, this is the right way to do it.
Or is there somekind of relationship merger/rule that I can use to say
all those columns are foreign keys to productID
No, they are all different relationships.
without creating one to one relationships ?
Note that these are many-to-one, not one-to-one relationships, many PrebuiltSystems will have the same Processor
Yes it is fine to have multiple foreign keys. However, in your example, I'd still do it differently; if you have one column for each component type you limit yourself very much. What do you do with a multi-CPU-system? What with multiple harddisks etc.?
You should rather normalize the PrebuiltSystems table so that you have a link table which creates a n-to-n relationship to the products (e.g. each product can be part of any number of prebuilt systems, and each prebuilt system can have any number of products in it).

Should columns in a junction table be able to store null vales?

When creating a junction table in sql to handle a many-to-many releationship between two tables, should the foreign key columns in the junction table be able to store null values?
It is a bad idea to do that because it stores no information.
A junction table is a link between 2 tables. If a record exists, by definition it must have the id from both sides to make a "junction" link. Otherwise it carries no useful information and is known as a waste-of-space.TM
No. It doesn't make sense to store a row representing the absence of a relationship in a table you designed to store the presence of relationships.
In addition to the other answers:
the two columns referencing the other tables are usually the primary key of that junction table. So per definition they cannot be null.
There are some circumstances where those columns do not make up the complete primary key (e.g. when having an attribute as part of the link and allowing multiple links with different attributes) - but then that attribute is part of the PK.

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