我需要一点帮助来用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}$如何将这些查询组合在一起?在
使用^{} ,或^{} :
使用}所有属性的选择),但是只获得赋值属性就可以了。在
as_scalar()
将返回的列和行限制为1,因此您无法使用它获得整个模型对象(因为query(PropertyValuation)
是{以后没必要通过。您当前声明子查询的方法很好,因为SQLAlchemy可以automatically correlate FROM objects to those of an enclosing query。我尝试创建某种程度上表示您所拥有的内容的模型,下面是上面的查询的工作原理(添加了换行符和缩进以提高可读性):
^{pr2}$相关问题 更多 >
编程相关推荐