2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-06-07

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()

参考

ありがてえ😘

途中で出会ったエラー

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

原因

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

など

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?