开发者

SqlAlchemy closure in subquery

开发者 https://www.devze.com 2023-04-02 07:52 出处:网络
I have searched many topics and didn\'t find the answer, or question was too complex. So okay. This is my first question.

I have searched many topics and didn't find the answer, or question was too complex. So okay. This is my first question. Here is the SQL

SELECT  parent.*,
(
    SELECT  COUNT(*)
    FROM    child
    WHERE   parent.id = child.parent_id
)
FROM parent

How to do 开发者_JAVA百科this clause in sqlalchemy?

WHERE   ui.invited_by = u.id

Can it be reproduced in collections ? sql expressions ? P.S. I know that it can be done by group_by. But i need by subquery.

Thank you.


The SA query (using subquery) will give you the results you want:

sq = session.query(Child.parent_id, func.count(Child.id).label("child_num")).group_by(Child.parent_id)
sq = sq.subquery()
# use outerjoin to have also those Parents with 0 (zero) children
q = session.query(Parent, sq.c.child_num).outerjoin(sq)
q = q.filter(Parent.id == 1) # add your filter here: ui.invited_by = u.id
for x in q.all():
    print x

although the subquery is not exactly as you described, but rather something like:

SELECT      parent.*,
            anon_1.child_num AS anon_1_child_num 
FROM        parent 
LEFT JOIN  (SELECT  child.parent_id AS parent_id, 
                    count(child.id) AS child_num 
            FROM    child 
            GROUP BY child.parent_id
            ) AS anon_1
        ON parent.id = anon_1.parent_id

Still do not understand why you need a sub-query the way you described though.


I find here really awesome answer. But too also too complicated. First of all i want to tell that closure in sql world is CORRELATION.

This is NOT the same but helps me.

pparent = Parent.__table__.alias('pparent') # using table directly to alias.

subquery = s.query(count(Child.id)).join(pparent) # usual thing but use aliased table.

s.query(Parent, subquery.filter(Parent.id == pparent.id).correlate(Parent).as_scalar()) #magic
0

精彩评论

暂无评论...
验证码 换一张
取 消