python - SQLAlchemy 编写嵌套查询

标签 python mysql sqlalchemy

我有两个表:

table A

id | values

table B

id | foreign key to A | datestamp | val2

给定 Aid 列表,我如何获得 AB 的合并结果> 只有 B 中每个匹配的 A 具有最早 datestamp 的行。

例如表 B 可能有:

1 | 2 | 1/10/2015
1 | 2 | 1/2/2015
1 | 2 | 1/3/2015

我只对行感兴趣

id_A | id_B | 1/2/2015 | values | val2

根据我对 SQL 的理解,你可以做类似的事情

where timestamp = (select min(timestamp) from B.X where x.id = b.id)

但是,如何将此选择嵌套在 SQLAlchemy 查询中?

例如,我相信我不能只使用

.filter(B.timestamp == (query(func.min(B.timestamp)).filter(A.id == B.foreign_key_to_A)))

最佳答案

实际上,您可以只使用:

B2 = aliased(B, name='b2')
s = session.query(func.min(B2.datestamp)).filter(B2.a_id == A.id)
q = (session
     .query(A.id, B.id, B.datestamp, A.values, B.val2)
     .join(B)
     .filter(B.datestamp == s)
     )

关于python - SQLAlchemy 编写嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31486689/

相关文章:

python - 将 float 写入文件时如何减少小数点后的位数?

python - 一次性运行操作应该放在Django框架的什么地方呢?

Mysql - 按月分组,格式为 Y-m-d

mysql - 如何在某些状态更改时排除增加 counter_cache?

python - 如何根据 postgresql 中的列值定义唯一约束?

python - sqlalchemy + MySQL 连接超时

python - 保留句子的标点符号,但删除不敬信息的所有特殊字符 Python

php - 从数据库读取值后显示选中和未选中的复选框列表不起作用

python - Sqlalchemy 方言 DATERANGE 与 psycopg2.extras.DateRange 更改边界

mysql - 使用正则表达式的 Flask SQLAlchemy 过滤器