Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

sqlalchemyでselect句にサブクエリを指定する

More than 1 year has passed since last update.

sqlalchemyでselect句にサブクエリを指定する

select
    table1.*,
    (select count(1) from table2 where table2.table1_id = table1.id group by table2.col1) as cnt
from table1
where ...;
count_stmt = session.query(func.count(1))\
    .filter(Table2.table1_id == Table1.id)\
    .group_by(Table2.col1)\
    .label('cnt')
session.query(Table1, count_stmt).filter(...).all()

参考

https://stackoverflow.com/questions/43654336/generate-sql-with-subquery-as-a-column-in-select-statement-using-sqlalchemy

ありがてえ😘

途中で出会ったエラー

sqlalchemy.exc.InvalidRequestError: Select statement '...' returned no FROM clauses due to auto-correlation; specify correlate(<tables>) to control correlation manually.

原因

  • サブクエリの.label()を書き忘れていた
  • join句を忘れていた

など

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away