Can anyone explain how to implement one-to-one, one-to-many and many-to-many relationships while designing tables with some examples?
One-to-one: Use a foreign key to the referenced table:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Many-to-many: Use a junction table (example):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Example queries:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
Here are some real-world examples of the types of relationships:
One-to-one (1:1)
A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.
To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).
For example:
CREATE TABLE Gov(
GID number(6) PRIMARY KEY,
Name varchar2(25),
Address varchar2(30),
TermBegin date,
TermEnd date
);
CREATE TABLE State(
SID number(3) PRIMARY KEY,
StateName varchar2(15),
Population number(10),
SGID Number(4) REFERENCES Gov(GID),
CONSTRAINT GOV_SDID UNIQUE (SGID)
);
INSERT INTO gov(GID, Name, Address, TermBegin)
values(110, 'Bob', '123 Any St', '1-Jan-2009');
INSERT INTO STATE values(111, 'Virginia', 2000000, 110);
One-to-many (1:M)
A relationship is one-to-many if and only if one record from table A is
related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.
To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).
For example:
CREATE TABLE Vendor(
VendorNumber number(4) PRIMARY KEY,
Name varchar2(20),
Address varchar2(20),
City varchar2(15),
Street varchar2(2),
ZipCode varchar2(10),
Contact varchar2(16),
PhoneNumber varchar2(12),
Status varchar2(8),
StampDate date
);
CREATE TABLE Inventory(
Item varchar2(6) PRIMARY KEY,
Description varchar2(30),
CurrentQuantity number(4) NOT NULL,
VendorNumber number(2) REFERENCES Vendor(VendorNumber),
ReorderQuantity number(3) NOT NULL
);
Many-to-many (M:M)
A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.
To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.
CREATE TABLE Class(
ClassID varchar2(10) PRIMARY KEY,
Title varchar2(30),
Instructor varchar2(30),
Day varchar2(15),
Time varchar2(10)
);
CREATE TABLE Student(
StudentID varchar2(15) PRIMARY KEY,
Name varchar2(35),
Major varchar2(35),
ClassYear varchar2(10),
Status varchar2(10)
);
CREATE TABLE ClassStudentRelation(
StudentID varchar2(15) NOT NULL,
ClassID varchar2(14) NOT NULL,
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
UNIQUE (StudentID, ClassID)
);
One-to-many
The one-to-many table relationship looks as follows:
In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key column in the child which references the Primary Key of the parent table row.
In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_comment
ADD CONSTRAINT
fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
One-to-one
The one-to-one table relationship looks as follows:
In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.
Therefore, we can say that the child table shares the Primary Key with the parent table.
In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_details
ADD CONSTRAINT
fk_post_details_id
FOREIGN KEY (id) REFERENCES post
Many-to-many
The many-to-many table relationship looks as follows:
In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.
In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post
And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag
One to one (1-1) relationship:
This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship:
This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- 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 table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
Related
I have two tables: Employee (ID, Name, Address) and Store(ID,Address) and I would like to record information about people who work in each store.
I thought of making a new table called Employee_List table. My questions:
1- Employee_List and Employee has one-to-many relation, right?
2- Employee_list to store has one-to-one relation, right?
3- How to define foreign and primary keys for Employee_List table?
Employee_list should have:
employee_listid (INT PK)
employee_id (INT FK)
store_id (INT FK)
I would recommend changing the table name to represent the composite table, i.e.
EmployeeStores. This would allow your schema to be scalable, employees can work in multiple stores.
In SQL Server:
CREATE TABLE EmployeeStores
(
EMPLOYEEStoreID INT IDENTITY,
EMPLOYEEID INT FOREIGN KEY REFERENCES Employee(employee_id),
STOREID INT FOREIGN KEY REFERENCES Store(store_id)
)
I have got 3 different tables:
review table-> this has mov_id as the primary key.
users_table -> this has username as the primary key.
review_table -> can I make a composite primary key for this table from movie_id and username?
users table
reviews table
comments table
I can't connect these 3 tables and I can't figure out why.
This is the error I'm getting while creating the comments table
You can create composite primary key with foreign keys (primary keys from others tables), you have nothing special to do. Just constrain the foreign keys and declare them as primary.
With the names of tables and columns you provided, here's a query to create the table you want :
CREATE TABLE review_table (
movie_id INT,
username VARCHAR(255),
-- Change INT and VARCHAR(255) by what you used on the others tables
PRIMARY KEY (movie_id, username),
FOREIGN KEY (movie_id) REFERENCES movies_table(movie_id),
FOREIGN KEY (username) REFERENCES users_table(username)
)
I want to make doctorid a foreign key in my patient table.
So I have all of my tables created - the main problem is that when I go to the table > structure > relation view only the primary key comes up that I can create a foreign key (and it is already the primary key of the certain table that I want to keep - i.e Patient table patient is enabled to be changed but the doctor Id -I have a doctor table also- is not enabled).
I have another table with two composite keys (medicineid and patientid) in relation view it enables me to change both
Do I have to chance the index of doctor ID in patient table to something else? both cannot be primary keys as patient ID is the primary for the patient table - doctor is the foreign.
I hope anyone can help
Kind regards
You can do it the old fashioned way... with an SQL statement that looks something like this
ALTER TABLE table_1_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (table_1_column_name)
REFERENCES target_table(target_table_column_name);
For example:
If you have books table with column created_by which refers to column id in users table:
ALTER TABLE books
ADD CONSTRAINT books_FK_1
FOREIGN KEY (created_by)
REFERENCES users(id);
This assumes the keys already exist in the relevant table
The key must be indexed to apply foreign key constraint. To do that follow the steps.
Open table structure. (2nd tab)
See the last column action where multiples action options are there. Click on Index, this will make the column indexed.
Open relation view and add foreign key constraint.
You will be able to assign DOCTOR_ID as foreign now.
To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab.
Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.
Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.
See attachments. I hope this could be useful for anyone.
Create a categories table:
CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
Create a products table and reference categories table:
CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;
Create a vendors table and modify products table:
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key (referencing vendors table) to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
If you wish to drop that key then:
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
In phpmyadmin, Go to Structure tab, select Relation view as shown in image below.
Here you will find the tabular form to add foreign key constrain name, current table column, foreign key database, table and column
Im just having trouble adding foreign key data between multiple tables in MySql, The tables are already created with the FK constraints in place. E.g. Ive created the following table:
$tbl_transactions = "CREATE TABLE IF NOT EXISTS transactions (
transaction_id INTEGER AUTO_INCREMENT PRIMARY KEY,
datetime DATETIME DEFAULT NOW(),
device_id INTEGER NOT NULL,
quantity INT(11) NOT NULL,
type_id INTEGER,
ticket_id INTEGER,
region_id INTEGER,
user_id INTEGER,
FOREIGN KEY (device_id) REFERENCES stock(device_id),
FOREIGN KEY (type_id) REFERENCES transaction_type(type_id),
FOREIGN KEY (ticket_id) REFERENCES tickets(ticket_id),
FOREIGN KEY (region_id) REFERENCES regions(region_id),
FOREIGN KEY (user_id) REFERENCES user_accounts(user_id)
)";
Ive also already created the tables: stock, transactions_type, tickets, regions and user_accounts and just need to add data into the above transactions table that specifically references the primary keys of the 5 foreign key tables.
I know the sql statement will start as follows:
$sql = 'INSERT INTO transactions (datetime, device_id, quantity, type_id, ticket_id, region_id, user_id)
VALUES...
Then im stuck, online examples seem to only discuss creating the tables rather than adding data into the tables.
Any help or suggestions would be greatly appreciated.
Thank you.
How can I relate a table with multiple records from another table?
Basically, I have a table for an 'event', how do I keep track of which 'users' (in their own seperate table) are in a particular event? Right now I just have a column in the 'event' table with a comma separated list of the users IDs who have joined that 'event'.
There must be a better way to do this...right?
Typically you have a table called users_in_event which holds one row for each user in a many-to-many relationship with the events table. So for each event, you will have a number of table rows mapped individually to users.
CREATE TABLE users_in_event
(
user_id INT,
event_id INT,
FOREIGN KEY user_id REFERENCES users (user_id) ON UPDATE CASCADE,
FOREIGN KEY event_id REFERENCES events (event_id) ON UPDATE CASCADE
-- Optionally, use ON DELETE CASCADE for the events foreign key
-- FOREIGN KEY event_id REFERENCES events (event_id) ON UPDATE CASCADE ON DELETE CASCADE
)
To find out which users are in an event, do:
SELECT
users_in_event.user_id,
users.name
FROM users JOIN users_in_event ON users.user_id = users_in_event.user_id
WHERE event_id=1234;
If you have a many-to-many relationship, that is, users can attend many events, and events can be attended by many users, that would traditionally be represented with a mapping table with the primary key from each table, plus any attributes specific to the user-event relationship.
For example, if you have ID columns in your USER and EVENT tables that are both type INT:
CREATE TABLE USER_EVENT_MAPPING
(
USER_ID INT,
EVENT_ID INT
)