Flask-SQLAlchemy使用小结

链表查询

join方法允许你指定两个或多个表之间的连接条件,并返回一个新的查询对象,该对象包含了连接后的结果。

内连接

from sqlalchemy import join

使用join函数

query = db.session.query(User, Order).join(Order, User.id == Order.user_id)

results = query.all()

或者使用Query对象的join方法

query = db.session.query(User, Order).join(Order, User.id == Order.user_id)

results = query.all()

遍历结果

for user, order in results:

print(user.username, order.order_id) # 假设Order表有一个order_id字段

左连接

query = db.session.query(User, Order).outerjoin(Order, User.id == Order.user_id)

results = query.all()

遍历结果,注意这里可能有些User没有对应的Order

for user, order in results:

if order is not None:

print(user.username, order.order_id)

else:

print(user.username, "No orders")

通过左连接,查询dialogue_detail和detail_eval表;

复制代码
conditions = [DialogueDetail.dialog_id == dialog_id,
              DialogueDetail.create_by == get_user_id()]
dialog_detail_fields = ["id", "dialog_id", "content", "dialog_role",
                        "user_source", "create_by", "create_time", "is_delete"]
detail_eval_fields = ["comment_type", "feedback_type", "feedback_content"]
query = (db.session.query(*[getattr(DialogueDetail, f1) for f1 in dialog_detail_fields],
                          *[getattr(DialogueDetailEvaluation, f2) for f2 in detail_eval_fields]).
         join(DialogueDetailEvaluation,
              DialogueDetailEvaluation.dialog_detail_id == DialogueDetail.id,
              isouter=True).
         filter(*conditions).order_by(DialogueDetail.create_time))

tmp_all = query.all()

多表连接

假设还有第三个表Product,Order表有一个product_id字段指向Product表的id字段

query = db.session.query(User, Order, Product).join(Order, User.id ==Order.user_id).join(Product, Order.product_id == Product.id)

results = query.all()

遍历结果

for user, order, product in results:

print(user.username, order.order_id, product.name) # 假设Product表有一个name字段

参考:

如何在SQLAlchemy中实现多表联合查询_sqlalchemy 对子查询join-CSDN博客

相关推荐
愤豆24 分钟前
05-Java语言核心-语法特性--模块化系统详解
java·开发语言·python
AI-Ming37 分钟前
程序员转行学习 AI 大模型: 踩坑记录:服务器内存不够,程序被killed
服务器·人工智能·python·gpt·深度学习·学习·agi
2401_873544921 小时前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
njidf1 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
只与明月听1 小时前
RAG深入学习之向量数据库
前端·人工智能·python
极光代码工作室2 小时前
基于Hadoop的日志数据分析系统设计
大数据·hadoop·python·数据分析·数据可视化
AAI机器之心2 小时前
这个RAG框架绝了:无论多少跳,LLM只调用两次,成本暴降
人工智能·python·ai·llm·agent·产品经理·rag
Fairy要carry2 小时前
项目01-手搓Agent之loop
前端·javascript·python
郝学胜-神的一滴2 小时前
【技术实战】500G单行大文件读取难题破解!生成器+自定义函数最优方案解析
开发语言·python·程序人生·面试
愤豆2 小时前
02-Java语言核心-语法特性-注解体系详解
java·开发语言·python