Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy closure in subquery

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 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.

like image 946
enomad Avatar asked Nov 05 '22 15:11

enomad


1 Answers

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.

like image 105
van Avatar answered Nov 09 '22 16:11

van