How to implement ER Relationships :One to one, One To Many, Many to Many in Oracle? - sql

Perhaps, this could seem like the basics of database design.But,certainly i find these concepts a lil tricky in the sense that how they relate to each other.
Theory as per my understanding.
One to One :
When each particular entity has one record.
One to Many :
When each particular entity has many record
Many to Many :
Multiple entities have multiple records.
As per the above if i could relate an example as
ONE TO ONE
Each employee having a unique passport number.
Table Employee
Empid(pk)
empname
passpordid(fk to passport)
Table passport
passportid(pk)
passportno
ONE TO MANY
An organisation having multiple employees
TABLE ORGANISATION
ORGID (PK)
ORGNAME
EMPID (FK TO EMPLOYEE)
TABLE EMPLOYEE
EMPID (PK)
EMPNAME
SALARY
This is the part that i want to know more that is many to many. I mean if we see one to many here. As a whole it could be said as many to many as many organisations having many employees but does that mean the whole relationship is many to many not one to many or one to many is a subset of many to many in the above example.
I wanna know the difference mainly between one to many and many to many both theoritically and by implementation.

An example of a many-to-many relationship would be EMPLOYEES and SKILLS, where SKILLS are things like "SQL", "Javascript", "Management" etc. An employee may have many skills (e.g. may know SQL and Javascript), and a particular skill by be possessed by many employees (e.g. Jack and Jill both know SQL).
In a database like Oracle, you need a third table to express the many-to-many relationship between EMPLOYEES and SKILLS:
create table EMPLOYEE_SKILLS
( empid references EMPLOYEES
, skillid references SKILLS
, constraint EMPLOYEE_SKILLS_PK primary key (empid, skillid)
);
Note that this third table has a foreign key to both of the other tables.
The table can also hold further information about the relationship - for example:
create table EMPLOYEE_SKILLS
( empid references EMPLOYEES
, skillid references SKILLS
, rating number
, date_certified date
, constraint EMPLOYEE_SKILLS_PK primary key (empid, skillid)
);

This is more a theory question that a programming one, but why not.
You could imagine a "many to many" as 1 table being a list of employees, and another table being a list of products sold.
Each employee is likely to "handle" more than 1 product, and each product could very well be handled by multiple employees, and it's quite possible that products A and B can be handled by, at the same time, employees C and D.

You seem to have the basic idea of one-to-one and one-to many down, in theory.
One-to-one: each item A has a separate and unique item B
In a database, you could include the new data in the same table. You could put it in a separate table, and enforce the one-to-one constraint by making the id into the remote table "unique" (indexing constraint), forcing the id for item B to not be repeated in the table. In your example, this would be a constraint added to the passportid.
One to many: each item A has some number of item Bs
In a database, you put the key in the table on the "many" side. So many Bs would have the same foreign key into table A. In your example, put an orgid as a foireign key into the employee table. Many employees can then point to a single organization, and an employee can belong to one organization.
Many to many: some number of As can be linked to any number of Bs and vice-versa
In a database, this is usually implemented as a link table, having just the IDs from both A and B. Following you example, consider that an employee can be part of multiple groups (or projects), multitasking across those groups. You could have a group table:
GROUPID (PK)
GROUPNAME
And the link table would then look like
LINKID (PK)
EMPID (FK TO EMPLOYEE)
GROUPID (FK TO GROUP)
This lets any employee be part of any number of groups, and groups to have any number of employees, AKA many-to-many.
A side comment:
Technically, you don't HAVE to have a LINKID in the link table. But it makes it easier to manage the data in that table, and is generally considered "best practice".

Related

Many to many relationship with several tables

I have the following tables
Company:
Id,Name
Person:
Id,Name
A company can have one or more directors. A director can be either another company or a person.
To link them I have a table Director:
Director: Id,CompanyId,DirectorCompanyId,PersonId
where if a company is a director DirectorCompanyId has a value and PersonId is null or if a Person is a director PersonId has a value and DirectorCompanyId is null
But I feel like this is not a correct design.
You're right, it's not a correct design. To decompose a M:M relationship into two 1:M relationships you need a third table:
CompanyPerson
--these columns are vital to decompose the many:many relationship
--the PK of this table should be a compound of these two columns
--so that the same person cannot twice work for the same company
--with different roles etc
PersonID -> FK to Person.ID
CompanyID -> FK to Company.ID
--plus other properties like:
RoleID -> FK to Role table --if roles are a defined set of options
StartDate -> --when the person began this employment
ManagerPersonId -> --the person's mananger.. etc
PersonID + CompanyID is the composite primary key for this table
It maps people to companies and the role they have at each. Can also have other info like start date, manager at that Company etc.. (might also need to make start date part of primary key if a person will ever leave and come back to the same co, and you wanted to recycle the PersonID)
Note: You could call this table Employee, because that's effectively what the people inside it are, but I tend to find it more helpful that these middle-man tables that create associations between two other tables are better off called Table1Table2 because you can more clearly see/understand the relationship/purpose of the table than if it's called something more abstract like Employee
The following design seems to be corresponding to demands
Another option is to use inheritance:
Director <-- CompanyDirector
<-- PersonDirector

sql primary key "mapping table ?"

i have a database for university so the students take many courses but each student have id as primary key also each course have an id as primary key its not allowed to have duplicate id at same table what should i use to make a table that same id but different courses id
In a normalized relational database, when you have a situation where items from one table can be associated with many items in a second table, and likewise those related items can be associated with many items in the first table, you should use a third table to store those relationships. In your case, that table might be called Enrollments.
You can use JOIN operations on that third table to relate, group, and aggregate across that relationship. You can also store any metadata associated with that relationship in the JOIN- table, for example you might store the enrollment date there.
Like vicatcu said, create a third table
Course_id | Student_id
The ID's of the courses and the students are uniq in their own tables. The relation between course < - > student is stored in that third table.

How to model many-to-many relationships in SQL?

I have a major problem with my SQL design.
I need to create a database which models the following situation:
I have a list of capitals, it looks like this: Berlin, London, Prague, you get it. The other list is a list of travellers: John, Kyle, Peter etc.
The database needs to be able to answer queries such as: List of cities a given Traveller has visited, what Travellers has visited a given City and so on.
My problem is that when I create the two tables I just freeze and am unable to figure out the connection between them that would allow me to implement the intended behaviour.
I read up on it on the internet and I was told to use intersection entities, which I can, but I just don't see how that would help me. Sorry if this is a FAQ, but I just could not get my head around the proper keywords for a search.
Isn't it easier to create third table like travelers_cities with to foreign keys traveler and city, than you jan join that table with table you need and look for result there?
Solution:
Follow the following schema
First Table: Capital
Let say two columns: cid (Primary Key), Name
Second Table: Travellers
Let say two columns: tid (Primary Key), Traveller_Name
Now there is a many to many relationship that one traveller can travel/visit one or many capitals and one capital can be visited by one or many visitors.
Many to many relationship can be acheived by creating a new table which will act as reference/mapping table. let say "capital_travellers"
So, This third table will have following columns
capital_travellers:
id (Primary key): Its optional
cid (Primary key of Capital Table will work as Foreign key)
tid (Primary key of traveller Table will work as Foreign key)
Now when you want to fetch records, you will look into this table(capital_travellers).
I hope it helps.
In a many to many relationship it is necessary to implement a third junction table between the two entities. We could, say, name it travel. This table uses two foreign keys, one from each entity, to form one compound key.
Now you have 3 tables. One table called 'Traveller', one called called 'City' and a third junction table called 'Travel'. Lets assume the primary key for traveller is travellerId and for city it's cityId. The junction table takes these two keys to form a primary key for the entity 'Travel'. When u query the database for which cities a traveller with travelId '031' has travelled to it would make use of this junction table and return the cityId's to you.
If this doesn't help or if you need more clarification I recommend searching these terms:
Many-to-many
Cardinality

A table with all attributes making the primary key

I have two tables: Student and Shop and I would like to record information about which student visited which shop and if the number of visits is above n, they should received a discount:
This is how I did it:
All of attributes (studentID, shopID, time, date) in table StudentShop makes the primary key for this table. I just wanted to know if this design is good?
As relation between entieties Student - Shop is many to many relationship,
it is always implemented using associative table (consists of primary keys from both relations), so StudentShop table - is good choice for implementation of such relation.

Include a foreign key column in the table?

I have the following situation. My table is:
Table: CompanyEmployees
EmployeeID
Date of Birth
Date Joined
I also want to store the sales information for each employee. I have this:
Table: DealsCompleted
ID
EmployeeID
Deal Name
Deal Amount
My question is this- should there be a column in CompanyEmployees called "DealsCompletedID" which directly refers to the ID column in DealsCompleted, or is it acceptabe to just create a foreign key between the two Employee ID columns? Does this disadvantage the design or potentially distort the normalization?
I am unclear what the rule is as to whether I should include an extra column in CompanyEmployees or not.
EDIT Please assume there will only be one row in the deal table, per employee.
A FOREIGN KEY should point from one table to its referenced row in a parent table, the two tables should generally not reference each other (with foreign keys defined in both).
The FOREIGN KEY is most appropriately defined in the DealsCompleted table, which points back to CompanyEmployees.EmployeeID. Think about it this way - The CompanyEmployees table stores information about employees. Deals they completed do not really count as information about employees. However, the employee who completed a deal is a part of the information about a deal, so the key belongs there.
Having DealsCompleted.EmployeeID will allow for a proper one to many relationship between employees and deals. That is, one employee can have as many related rows in DealsCompleted as needed. Including a DealsCompleted column in the CompanyEmployees table on the other hand, would require you to either duplicate rows about employees, which breaks normalization, or include multiple DealCompletedID values in one column which is also incorrect.
Update after edit above Even if you plan for only a one-to-one relationship (one deal per employee), it is still more appropriate to reference the EmployeeID in DealsCompleted rather than the other way around (or both ways). ...And it allows you to expand to one-to-many, when the need arises.
Assuming that the relationship will always be one-to-one, as you state, then the answer depends on what is the primary entity within the Domain Model. If this database is at its core a database about Deals, and employee data is ancillary, then I would add an EmployeeId FK column in the Deal table. If otoh, this is a database about Employees, and Deals are ancillary, then eliminate the EmployeeId column in the Deal table, and add a DealId FK column to the Employeee table.