首页 > 解决方案 > SQLAlchemy 获取自某个值以来的最后一行

问题描述

自上次将某个值添加到数据库以来,我正在寻找一种获取所有行的方法。例如:

+--------+--------+--------+ 
| created| status |   my_id|
+--------+--------+--------+
| ...    | success|       3|
| ...    | fail   |       3|
| ....   | success|       3|
| ....   | fail   |       3|
| ....   | fail   |       3|
+--------|--------+--------+

给定下表,我的查询将提取最后两行,例如“给我自从我上次看到成功状态以来的最后几行”

极端案例:如果没有成功案例,则应返回所有行。如果最后一行成功,则不返回任何内容或 None 或其他内容。

我不知道从哪里开始。我不能按日期订购,因为这会打乱订购。在一个查询中执行此操作将是最优雅的,例如

#Get the last success ?
subq = (db.session.query(MyObject.status, MyObject.created, MyObject.my_id).group_by(my_id).filter_by(status=="success").order_by(created.desc)
 .subquery())
(db.session.query(MyObject).join(
    subq, #Last success
    and_(MyObject.created >= sub.c.created)
    ).filter_by(status=="fail").all())

编辑:创建的形式如下:created = Column(types.DateTime, nullable=False, default=datetime.utcnow)

这是数据库表的摘录,其中显示了一些值:

id  created             status  my_id
1   2020-11-26 16:09:03 failed  3
2   2020-11-26 16:12:03 failed  3
3   2020-11-26 16:15:03 failed  3
4   2020-11-26 16:18:04 failed  3
5   2020-11-26 16:21:04 failed  3
6   2020-11-26 16:24:04 failed  3
7   2020-11-26 16:27:04 failed  3
8   2020-11-26 16:30:05 failed  3
9   2020-11-26 16:33:00 failed  3
10  2020-11-26 16:36:00 failed  3
11  2020-11-26 16:39:01 failed  3
12  2020-11-26 16:42:01 failed  3
13  2020-11-26 16:45:01 failed  3
14  2020-11-26 16:48:01 failed  3
15  2020-11-26 16:51:02 failed  3
16  2020-11-26 16:54:02 failed  3
17  2020-11-26 16:57:02 failed  3
18  2020-11-26 17:00:08 failed  3

编辑2:

我已经管理了一个查询,以确定我们何时确定某处成功:

subq = db.session.query(MyObj).filter_by(status="success", my_id=3). order_by (MyObj.id.desc()).limit(1).subquery("t2"))
q = MyObj.query.join(subq, and_(MyObj.status=="failed", MyObj.id > subq.c.id)).all()

然而,这并不能解决“一切都失败”的问题。

标签: pythonpostgresqlsqlalchemy

解决方案


我认为这样的事情应该有效

subq = (session.query(sa.func.coalesce(sa.func.max(MyObject.created), dt.datetime.min))
               .filter_by(status='success').scalar())

q = (session.query(MyObject)
            .filter(MyObject.created >= subq)
            .filter(MyObject.status == 'failed'))

在子查询中,我们使用 . 返回最大的“成功”日期MAX(created)。如果没有“成功”行,则改为COALESCE供应datetime.datetime.min。我们返回 ascalar以便我们可以比较过滤器中的值。


推荐阅读