[英]Python Sqlite how to print data from different table using foreign key?
I'm new to sqlite in python and I can't seem to work out why the foreign key isn't working? 我是python中的sqlite的新手,我似乎无法弄清楚为什么外键不起作用? What do I need to do?
我需要做什么? I want to print details from a different table!
我想从不同的表格打印细节! help!
救命!
c.execute("PRAGMA foreign_keys = ON")
c.execute('''CREATE TABLE IF NOT EXISTS Staff
(staff_id integer UNIQUE,
staff_name text,
staff_DOB date,
staff_gender text,
Primary Key(staff_id)
)
''')
c.execute('''CREATE TABLE IF NOT EXISTS Clients
(client_id integer UNIQUE,
client_name text,
client_DOB date,
client_gender text,
staff integer,
Primary Key(client_id),
FOREIGN KEY(staff) REFERENCES Staff(staff_id)
)
''')
c.execute('''INSERT INTO Staff (staff_name,staff_DOB,staff_gender) VALUES ("joe","24/09/1999","male")''')
c.execute('''INSERT INTO Clients (client_name,client_DOB,client_gender, staff) VALUES ("sarah","12/09/2001","female",1)''')
c.execute("SELECT staff_name FROM Clients")
data = c.fetchone()
print(data)
You will need to JOIN
the tables by the foreign key. 您需要通过外键来
JOIN
表。
For example: 例如:
SELECT
t1.*,
t2.staff_name
FROM Clients t1
LEFT JOIN Staff t2
ON (t2.id = t1.staff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.