如何将SQL标量子查询转换为SQLAlchemy表达式

2024-09-28 01:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一点帮助来用SQLAlchemy语言表达我的代码,如下所示:

SELECT
    s.agent_id,
    s.property_id,
    p.address_zip,
    (
        SELECT v.valuation
        FROM property_valuations v WHERE v.zip_code = p.address_zip
        ORDER BY ABS(DATEDIFF(v.as_of, s.date_sold))
        LIMIT 1
    ) AS back_valuation,
FROM sales s
JOIN properties p ON s.property_id = p.id

内部子查询的目的是从表sales中获取与销售日期最近的列(zip_code INT, valuation DECIMAL, as_if DATE)的表propert_valuations的属性值。我知道如何重写它,但我完全停留在order_by表达式上—我不能准备子查询稍后传递排序成员。在

目前我有以下疑问:

^{pr2}$

如何将这些查询组合在一起?在


Tags: 代码fromidsqlalchemyaddressascodeproperty
1条回答
网友
1楼 · 发布于 2024-09-28 01:22:53

How to combine these queries together?

使用^{},或^{}

subquery = (
    session.query(PropertyValuation.valuation)
    .filter(PropertyValuation.zip_code == Property.address_zip)
    .order_by(func.abs(func.datediff(PropertyValuation.as_of, Sale.date_sold)))
    .limit(1)
)

query = session.query(Sale.agent_id,
                      Sale.property_id,
                      Property.address_zip,
                      # `subquery.as_scalar()` or
                      subquery.label('back_valuation'))\
        .join(Property)

使用as_scalar()将返回的列和行限制为1,因此您无法使用它获得整个模型对象(因为query(PropertyValuation)是{}所有属性的选择),但是只获得赋值属性就可以了。在

but I completely stuck on order_by expression - I cannot prepare subquery to pass ordering member later.

以后没必要通过。您当前声明子查询的方法很好,因为SQLAlchemy可以automatically correlate FROM objects to those of an enclosing query。我尝试创建某种程度上表示您所拥有的内容的模型,下面是上面的查询的工作原理(添加了换行符和缩进以提高可读性):

^{pr2}$

相关问题 更多 >

    热门问题