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博客

相关推荐
Goona_10 分钟前
拒绝SQL恐惧:用Python+pyqt打造任意Excel数据库查询系统
数据库·python·sql·excel·pyqt
xw33734095641 小时前
彩色转灰度的核心逻辑:三种经典方法及原理对比
人工智能·python·深度学习·opencv·计算机视觉
倔强青铜三1 小时前
为什么 self 与 super() 成了 Python 的永恒痛点?
人工智能·python·面试
墨尘游子1 小时前
目标导向的强化学习:问题定义与 HER 算法详解—强化学习(19)
人工智能·python·算法
小白学大数据2 小时前
基于Python的新闻爬虫:实时追踪行业动态
开发语言·爬虫·python
freed_Day2 小时前
python面向对象编程详解
开发语言·python
普郎特3 小时前
张三:从泥水匠到包工头的故事 *—— 深入浅出讲解 `run_in_executor()` 的工作原理*
python
我要学习别拦我~3 小时前
kaggle分析项目:steam付费游戏数据分析
python·游戏·数据分析
大模型真好玩3 小时前
深入浅出LangChain AI Agent智能体开发教程(四)—LangChain记忆存储与多轮对话机器人搭建
前端·人工智能·python
love530love3 小时前
命令行创建 UV 环境及本地化实战演示—— 基于《Python 多版本与开发环境治理架构设计》的最佳实践
开发语言·人工智能·windows·python·conda·uv