Python Sqlite如何使用外键从不同的表中打印数据?

时间:2019-03-21 20:01:15

标签: python python-3.x sqlite foreign-keys

我是python中的sqlite的新手,我似乎无法弄清楚为什么外键不起作用?我需要做什么?我想从其他表格打印详细信息!帮助!

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)

1 个答案:

答案 0 :(得分:0)

您将需要使用外键JOIN表。

例如:

SELECT
t1.*,
t2.staff_name
FROM Clients t1
LEFT JOIN Staff t2
ON (t2.id = t1.staff);