Different ways of implementing relationship between tables in oracle - mysql

I have seen ,implementing the relation between "States" and "Districts" in two ways:
The relation between States and Districts is one to many relationship respectively..
First way:
In this implementaion,take two tables "States" and "Districts" and implement the one to many relationship between States to District as put the foreign key in Districts table.
In my "States" table the columns are: state_id(pk) & state_name.
In my "Districts" table the columns are: district_id(pk) district_name state_id(fk).
Second Way:
In this implementaion,take two tables "States" and "Districts" and implement the one to many relationship between States to District as creating the third table "state_district" and implementing as follows.
In my "States" table the columns are: state_id(pk) & state_name.
In my "Districts" table the columns are: district_id(pk) district_name .
The third table is "state_district",the columns are s_did(pk), district_id(fk),state_id(fk).
What is the difference betwen these two mechanisms.

The difference is that in the first case there can be only one state per district, wheras in the second there can be many states per district.
Which one you should use depends entirely on whether a district can be associated with multiple states or not. If they can then you have to use the second many-to-many model. If they cannot then while in practice you could use the second model, it would be incorrect to do so -- you should use the first one-to-many model.

for one to many relationship we use a table's primary key as foreign key in another table - Which is your first approach ans correct in this case
For many to many relationship we use a third table to store the relationship between first 2 tables- which is not required in your case as state to district has one to many relationship

What is the difference between these two mechanisms.
The difference is that the second method allows a district to be associated with more than one state. You can do this by just adding another row for a given district in the third table.
INSERT INTO state_district (district_id, state_id) VALUES
(1234, 49), (1234, 50);
Now you have the same district 1234 associated with both Alaska (49) and Hawaii (50).
I would assume you don't really need this. In fact, it would be better to ensure that each district belongs to exactly one state. You should have only a one-to-many relationship between states and districts. So you should use the first design.

Your second way should be done if there is a many to many relationship between states to districts.
You first way is correct and you should implement.

I would propose the following table structures:
States: --don't need extra metadata such as the sequence generated value
state_name varchar2(50) PRIMARY KEY
Districts: -- don't need extra metadata
district_name varchar2(100) PRIMARY KEY
State_Districts
state_name varchar2(50)
district_name varchar2(100)
primary key (state_name,district_name)
This ensures that you don't have duplicate district names which are real unique identifiers, regardless of if Wyoming and Pennsylvania have the same district name, the data is independent of each other. This also ensures that there will be no null values in any of the three tables, this is pretty important when we think about normalization techniques.

It would appear from your first table definition of the two tables that there is a State ID field in the District table. This indicates to me that there are one or more districts per state. In this case, a third table would be redundant.

Related

Best way to create a multi relational database in my scenario

I'm having trouble to develop my database model.
I have the tables TOUR and TRIP (both with GUID primary key) and both have some children tables in common. Like DETAIL, COMMENT, MEDIA, PRICE and like that.
I'm thinking in create in those children tables some "ParentId" column to link with TOUR or TRIP, but I need to know which parent table is. In this way I should to create a column "ParentType" where 1 is TOUR and 2 is TRIP or maybe create a TourDetail and a TripDetail to link each one with other table?
I'm looking for the best practice to do that.
In terms of design, the SQL convention is that each relationship should have its own column in the referencing table. That's the concept if foreign key columns.
So you need to create two columns in each child table (DETAIL, COMMENT, MEDIA, PRICE), like TOUR_ID and TRIP_ID that will contain the primary key of the correspondig records in, respectively, tables TOUR and TRIP. Of course if a children refers to only one parent and not the other, only one column is necessary.
This will then allow you to build proper JOIN queries like :
SELECT
...
FROM TRIP
JOIN DETAIL on DETAIL.TRIP_ID = TRIP.ID
...
WHERE
...

MySQL : One to One Relationship Tables Merging

I am trying to simplify an application's database. In that database I have two tables let's say Patient and MedicalRecord. I know that two tables are said to be in One-to-One relationship iff that any given row from Table-A can have at most one row ine Table-B(It means there can be zero matchings).
But in my case, it is not at most, it is exactly. i.e., Every row in Patient should have exactly one row in MedicalRecord(no patient exist without a medical record).
Patient table has all personal details of the patient with his id as PK.
MedicalRecord talbe has details like his blood-group, haemoglobin, bp etc with his id as both PK and FK to the Patient.
My Question is, can I merge those two tables and create one table like,
PatientDetails : personal_details and blood-group, haemoglobin, bp etc
"bp" = "Blood pressure"? Then you must not combine the tables. Instead, it is 1:many -- each patient can have many sets of readings. It is very important to record and plot trends in the readings.
Put only truly constant values in the Patient -- name, birthdate (not age; compute that), sex, race (some races are more prone to certain diseases than others), not height/weight. Etc.
Sure, a patient may have a name change (marriage, legal action, etc), but that is an exception that does not affect the schema design, except to force you to use patient_id, not patient_name as a unique key.
Every patient must have a MedicalRecord? That is "business logic"; test it in the application; do not depend (in this case) on anything in the Database.
Both tables would have patient_id. Patients would have it as the PRIMARY KEY; MedicalRecord would haveINDEXed`. That's all it takes to have 1:many.
In situations where the tables are really 1:1 (optionally 1:0/1), I do recommend merging the table. (There are exceptions.)
If two tables have the same set of subrow values for a shared set of columns that is a superkey in both (SQL PRIMARY KEY or UNIQUE) then you can replace the two tables by their natural join. ("Natural join" is probably what you mean by "merge" but that is not a defined technical term.) Each original table will equal the projection of the join on that original's columns.
(1:1 means total on both sides, it does not mean 1:0-or-1, although most writing about cardinalities is sloppy & unclear.)

Is it necessary to bring the primary key of non repeating table while normalizing the database from UNF to 1NF

My UNF is
database(
manager_id,
manager_name,
{supplier_id,
supplier_name,
{order_id,
order_quantity}}
{purchase_id,
purchase_date}
Here manager_name, supplier_id, order_id and purchase_id are primary key.
During normalization there will be 1 table called purchase. Is it necessary to make manager_name as a foreign key?
How can I normalize these database?
This is a part of my college project on database. Normalization is really confusing.
First consider splitting things out by things that naturally go together. In this case you have manager information, supplier information, order information and purchase information. I personally would want to know the difference between an order and a purchase because that is not clear to me.
So you have at least four tables for those separate pieces of information (although depending on the other fields you might need, suppliers and managers could be in the same table with an additional field such as person_type to distinguish them, in this case you would want a lookup table to grab the valid person type values from). Then you need to see how these things relate to each other. Are they in a one to one relationship or a one-to many or a many to many relationship? In a one-to one relationship, you need the FK to also have a unique constraint of index to maintain the uniqueness. In a many to many you will need an additional junction table that contains both ids.
Otherwise in the simplest case the child table of purchase would have FKs to the manager, supplier. and order tables.
Manager name should under no circumstances be a primary key. Many people have the same name. Use Manager ID as the key because it is unique where name is not. In general I prefer to separate out the names into First, middle and last so that you can sort on last name easily. However in some cultures this doesn't work so well.

Mysql composite primary key

I want to have a lookup table that links two of the same things to eachother. Say I have a 'Person' table and I want to lookup the relationship between two people. I'll have column one of the lookup be 'PersonId1' and column two be 'PersonId2' and the third column be 'Relationship'. Since the relationship goes both ways I don't need to have duplicate records with the PlayerId's switched. Is there any way to make mysql enforce uniqueness on PlayerId1 and PlayerId2 combinations regardless of which order they're in?
Does that make sense?
Short answer: No.
Longer answer: You could set up a trigger to swap the order of the two person ids if the second were smaller than the first, then write them, and use a composite key.
Even longer answer: Not all interpersonal relationships are commutative (not all relationships go both ways). What about the "Employee" or "Mother" relationships? Even the "Friend" relationship, which is presumably peer-to-peer, might be better represented if you had separate rows saying A is B's Friend and B is A's Friend. So maybe you want a three-field composite key on this table.
You mean you want to have a unique row record from PersonID1 and PersonID2 Column (regardless of the Relationship column)? If that so, you may use the Composite key (Multi column key).
Here's an example:
CREATE TABLE Person (
PersonId1 INT,
PersonId2 INT,
PRIMARY KEY (PersonId1, PersonId2)
)
+1 for composite pk. To prevent duplicate combinations, an extra varchar column with for example personid1+personid2 with a unique constraint on it may be a solution...
See also: person data model example

Meaning of "n:m" and "1:n" in database design

In database design what do n:m and 1:n mean?
Does it have anything to do with keys or relationships?
m:n is used to denote a many-to-many relationship (m objects on the other side related to n on the other) while 1:n refers to a one-to-many relationship (1 object on the other side related to n on the other).
1:n means 'one-to-many'; you have two tables, and each row of table A may be referenced by any number of rows in table B, but each row in table B can only reference one row in table A (or none at all).
n:m (or n:n) means 'many-to-many'; each row in table A can reference many rows in table B, and each row in table B can reference many rows in table A.
A 1:n relationship is typically modelled using a simple foreign key - one column in table A references a similar column in table B, typically the primary key. Since the primary key uniquely identifies exactly one row, this row can be referenced by many rows in table A, but each row in table A can only reference one row in table B.
A n:m relationship cannot be done this way; a common solution is to use a link table that contains two foreign key columns, one for each table it links. For each reference between table A and table B, one row is inserted into the link table, containing the IDs of the corresponding rows.
n:m --> if you dont know both n and m it is simply many to many and it is represented by a bridge table between 2 other tables like
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
this is the bridge table for implementing Mapping between 2 tables
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
One to Many (1:n) is simply one table which has a column as primary key and another table which has this column as a foreign key relationship
Kind of like Product and Product Category where one product Category can have Many products
In a relational database all types of relationships are represented in the same way: as relations. The candidate key(s) of each relation (and possibly other constraints as well) determine what kind of relationship is being represented. 1:n and m:n are two kinds of binary relationship:
C {Employee*,Company}
B {Book*,Author*}
In each case * designates the key attribute(s). {Book,Author} is a compound key.
C is a relation where each employee works for only one company but each company may have many employees (1:n):
B is a relation where a book can have many authors and an author may write many books (m:n):
Notice that the key constraints ensure that each employee can only be associated with one company whereas any combination of books and authors is permitted.
Other kinds of relationship are possible as well: n-ary (having more than two components); fixed cardinality (m:n where m and n are fixed constants or ranges); directional; and so on. William Kent in his book "Data and Reality" identifies at least 432 kinds - and that's just for binary relationships. In practice, the binary relationships 1:n and m:n are very common and are usually singled out as specially important in designing and understanding data models.
To explain the two concepts by example, imagine you have an order entry system for a bookstore. The mapping of orders to items is many to many (n:m) because each order can have multiple items, and each item can be ordered by multiple orders. On the other hand, a lookup between customers and order is one to many (1:n) because a customer can place more than one order, but an order is never for more than one customer.
What does the letter 'N' on a relationship line in an Entity Relationship diagram mean?
Any number
M:N
M - ordinality - describes the minimum (ordinal vs mandatory)
N - cardinality - describes the miximum
1:N (n=0,1,2,3...) one to zero or more
M:N (m and n=0,1,2,3...) zero or more to zero or more (many to many)
1:1 one to one
Find more here:
https://www.smartdraw.com/entity-relationship-diagram/
Many to Many (n:m)
One to Many (1:n)
Imagine you have have a Book model and a Page model,
1:N means:
One book can have **many** pages. One page can only be in **one** book.
N:N means:
One book can have **many** pages. And one page can be in **many** books.
m:n refers to a many to many relationship whereas 1:n means one to many relationship.
For example:
employee(id,name,skillset)
skillset(id,skillname,qualifications)
in this case the one employee can have many skills and ignoring other cases you can say that it's a 1:N relationship