Relationship Between Two Tables
Relationship Between Two Tables
Database is collection of one or more table which are related to each other. To illustrate the relating two
tables, I consider my3 database which already exist and contains employee table. In the same database
create project table which stores project details. Project table contain three field pid, name and hours.
Pid is primary key. Below python code is used to create project table and insert a records into a table.
#Following Python program will be used to create a table project in my3 database in which already
#employee table exists and insert records into project table
import sqlite3
conn = sqlite3.connect('c:\sqlite3\my3.db')
# );''')
conn.commit()
conn.close()
output:
C:\>cd sqlite3
C:\sqlite3>sqlite3 my3.db
);
888|Database Application|30.0
999|Mobile Application|25.0
Now create assign table which relates employee and project table. Employees are assigned to project.
Below code create a assign table in my3 database with pid1 and empid attributes. Pid1 is foreign key
refers to project table and empid is foreign key refers to employee table primary key.
#following Python program will be used to create a table assign in my3 database in which already
#employee and project table exists
import sqlite3
conn = sqlite3.connect('c:\sqlite3\my3.db')
#in assignment table empid and pid both are foreign keys referes to employee and project table
conn.execute("create table assign(pid1 int references project, empid int references employee)")
conn.close()
output:
CREATE TABLE assign(pid1 int references project, empid int references employee);
Next insert records into assign table. Records must be inserted without violating foreign key constraint.
i.e pid1 and empid in assign table must exist in project and employee respectively. To ensure this first
retrieve all empid and pids from both table and store it in list. When user input empid and pid for
inserting into a assign table check are they in list if yes then insert a record into a table. Below is user to
insert records into assign table.
import sqlite3
conn = sqlite3.connect('c:\sqlite3\my3.db')
le=[]
lp=[]
for k in r:
le.append(k[0])
for j in r1:
lp.append(j[0])
print(le)
print(lp)
k1=1
while k1==1:
e,p=input().split()
e,p=int(e),int(p)
if e in le and p in lp:
conn.commit()
else:
k1=input()
conn.close()
output:
[1, 5, 9, 38, 63, 78, 123, 576, 678, 777, 900, 11111]
999|38
777|63
888|576
999|900
888|9
We retrieve records from these three using natural join condition. In below python program first query
is used to retrieve name of employee assigned to a project and in second one is used to retrieve project
names assigned to a employee.
#join queries
import sqlite3
conn = sqlite3.connect('c:\sqlite3\my3.db')
for j in r:
print(j)
for k in r1:
print(k)
conn.close()
output:
('KAVERI',)
('shivu',)
('gfh',)
('RAGHU',)
('GAYATHRI',)
('Mobile Application',)
('Database Application',)
('Mobile Application',)
('Database Application',)