from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# 创建数据库连接
engine = create_engine('mysql://username:password@localhost/database_name')
Session = sessionmaker(bind=engine)
session = Session()
# 联表查询
query = session.query(ANNInspectionBatchTaskModel, ANNDistributionBatchTaskModel).\
filter(ANNInspectionBatchTaskModel.id == ANNDistributionBatchModel.task_id)
# 获取查询结果
results = query.all()
# 打印查询结果
for result in results:
ann_inspection_task = result[0]
ann_distribution_task = result[1]
print(ann_inspection_task.id, ann_inspection_task.other_field1, ann_inspection_task.other_field2,
ann_distribution_task.id, ann_distribution_task.task_id, ann_distribution_task.other_field3)
在上面的代码中,首先创建数据库连接并创建一个Session对象。然后使用session.query()方法指定要查询的两个模型类,并使用filter()方法指定关联条件。最后使用all()方法获取查询结果,并通过遍历结果获得每一行的数据。
# 联表查询,并指定需要的字段
query = session.query(BatchTaskModel.id,
BatchTaskModel.other_field1,
DistributionTaskModel.task_id,
DistributionTaskModel.other_field3
).(ANNInspectionBatchTaskModel.id == ANNDistributionBatchTaskModel.task_id)
# 获取查询结果
results = query.all()
# 打印查询结果
for result in results:
ann_inspection_id = result[0]
ann_inspection_other_field1 = result[1]
ann_distribution_task_id = result[2]
ann_distribution_other_field3 = result[3]
print(ann_inspection_id,_inspection_other_field1, ann_distribution_task_id, ann_distribution_other_field3)
在上述代码中,session.query() 方法中指定了需要的字段,然后通过遍历查询,可以获取每一行中指定字段的值。
实际上,当你在 session.query() 方法中指定了需要的字段,SQLAlchemy 会自动根据模型类的定义和关联条件来生成适当的联表查询语句,无需显式指定表名称。
在上述代码中,我们直接使用了结果对象的属性来获取指定字段的值,而无需指定表名称。SQLAlchemy ORM根据模型类的定义自动识别和映射表结构,并生成适当的联表查询语句。