简体   繁体   English

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

[英]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.

相关问题 插入到通过 FOREIGN KEY 链接到第二个表的 2 个表中,并从 sqlite 和 python 中的另一个表中获取数据 - insert into 2 table one linked to the second through FOREIGN KEY and take data from another table in sqlite and python 当使用SQLite的Python 2.7表中有外键时,不确定如何编写insert语句 - Not sure how to code insert statement when there is a foreign key in a table for Python 2.7 using SQLite 如何在由外键连接的不同表的模板 django 中打印数据? - How to print data in template django of a diffrent table joined by foreign key? SQLite-使用外键插入-Python - SQLite- Insert using foreign key - Python Python - 如何打印Sqlite表 - Python - How to print Sqlite table 使用外键映射使用Python和SQLAlchemy从另一个表中获取数据 - Use a foreign key mapping to get data from the other table using Python and SQLAlchemy 在Django中,如何使用外键将下拉列表与另一个表中的数据绑定? - In Django, how to bind the dropdown list with data from another table using foreign key? 如何使用外键过滤表中的数据? - How can I filter data from a table with a Foreign Key? 使用python使用外键插入Postgres表 - inserting into Postgres table with a foreign key using python django查询语句中如何通过外键和自然键显示不同表的字段 - How to show fields from different table through foreign key and natural key in django query statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM