SqlAlchemy ORM和聚合函数

时间:2017-03-10 09:18:22

标签: python postgresql orm sqlalchemy

我正在使用sqlalchemy ORM从Postgresql数据库中获取数据,我很想知道你是如何使用sqlalchemy ORM进行复杂查询的,如下所示:

select table1.name, Array(select name from table2 join table3 using(id) where param1=6949)
from table1
where param1=6949

1 个答案:

答案 0 :(得分:1)

您可以将ARRAY constructorgeneric functions一起使用。根据您对表的映射方式,可以是ORM模型,也可以是Table

# ORM mappings here
stmt = session.query(Table2.name).\
    join(Table3, Table2.id == Table3.id).\
    filter_by(param1=Table1.param1)

query = session.query(Table1.name,
                      func.array(stmt.as_scalar())).\
    filter_by(param1=6949)

ARRAY构造函数需要一个子查询生成一个列。子查询必须用作表达式,并且也可以从FROM对象列表中删除,这可以使用as_scalar()完成。

一个具体的例子:

In [2]: class Table1(MagicBase):
   ...:     name = Column(Unicode)
   ...:     param1 = Column(Integer)
   ...:     

In [3]: class Table2(MagicBase):
   ...:     name = Column(Unicode)
   ...:     

In [4]: class Table3(MagicBase):
   ...:     param1 = Column(Integer)
   ...:     

In [5]: stmt = session.query(Table2.name).\
   ...:     join(Table3, Table2.id == Table3.id).\
   ...:     filter_by(param1=Table1.param1)
   ...: 
   ...: query = session.query(Table1.name,
   ...:                       func.array(stmt.as_scalar())).\
   ...:     filter_by(param1=6949)
   ...: 

In [6]: print(query)
SELECT table1.name AS table1_name, array((SELECT table2.name 
FROM table2 JOIN table3 ON table2.id = table3.id 
WHERE table3.param1 = table1.param1)) AS array_1 
FROM table1 
WHERE table1.param1 = %(param1_1)s