0
0

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 3 years have passed since last update.

【PythonのORM】SQLAlchemyでIN句にサブクエリを用いたSQLを書くときの記法

Posted at

ORM? SQLAlchemy?

既に下記のようなQiita記事でもまとめているため、省略して本題のみ
https://qiita.com/tomo0/items/a762b1bc0f192a55eae8
https://qiita.com/ariku/items/75799665acd09520bed2

コード

url = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=%s' % (
    self.user,
    self.password,
    self.host,
    int(self.port),
    self.db,
    self.charset
)
self.engine = create_engine(url)
self.session = sessionmaker(bind=self.engine, autocommit=False, autoflush=True)()`

# IN句にサブクエリを含める
rows = db.session.query(User).filter(
  User.id.in_(
    db.session.query(UserItem.user_id).filter(
      UserItem.item_id == 1, UserItem.numbers > 10
    )
  )
).all()

下記のような

SELECT * FROM users WHERE id IN (
   SELECT user_id FROM user_items WHERE item_id = 1 AND numbers > 10
)

まとめ

SQLAlchemyではIN句にサブクエリを用いるSQLなどの複雑なSQLも表現可能

注意点として、ORMでは裏側でどういったSQLが発行されるかがブラックボックスであるため、微妙なSQLになっていないかデバッグ時はcreate_engine時に下記のようなオプションを追加しSQLを出力するようにしてチェックすることをオススメします

echo_option = 'DEBUG' in os.environ and os.environ['DEBUG'] == 'on'
self.engine = create_engine(url, echo=echo_option)
self.session = sessionmaker(bind=self.engine, autocommit=False, autoflush=True)()`
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?