将原始SQL转换为SQLAlchemy查询

时间:2014-12-02 23:00:28

标签: python sql database postgresql sqlalchemy

SELECT * 
FROM product_stocks 
WHERE detected_date = (
                         SELECT MAX(detected_date) 
                         FROM product_stocks 
                         WHERE id = 18865
                      ) 
      AND id = 18865;

将此转换为SQLAlchemy查询字符串时遇到很多麻烦。什么是最有效的方式?

3 个答案:

答案 0 :(得分:4)

您可以使用from_statement执行原始SQL查询并在SQL-Alchemy对象中获取它。当编写纯SQL然后SQLAlchemy语法时,这会有所帮助。

Session.query(YourClass).from_statement(text('''SELECT * FROM product_stocks 
WHERE detected_date = (SELECT MAX(detected_date) FROM product_stocks WHERE id = 18865)
AND id = 18865;''')).all()

答案 1 :(得分:2)

下面将重新创建您要求的SQL:

_id = 18865
T = aliased(ProductStock, name="T")
T1 = aliased(ProductStock, name="T1")
subquery = (
    session.query(func.max(T1.detected_date).label("detected_date"))
    .filter(T1.id == _id)
    # .filter(T1.id == T.id)  # @note: i prefer this one to the line above
    .as_scalar()
)
qry = (
    session.query(T)
    .filter(T.detected_date == subquery)
    .filter(T.id == _id)
)

这是实现您想要的最有效方式吗? - 我不太确定,但信息不足

答案 2 :(得分:0)

使用经典的SQLAlchemy:

sql = 'SELECT foo FROM bar'
sql = text(sql)
sql = sql.columns()  # This let's it be used as a subquery

sel = select(['foo']).select_from(sql)
# I needed this for a complex query or else columns would be ambiguous
sel = sel.alias('sel')  

joined = sel.outerjoin(baz_t, baz_t.foo==sel.foo)

final = select([sel.c.foo]).select_from(joined)

请注意,columns()是必要的,如果查询很复杂,alias()会很有用。

以下text文档很有帮助。