5
3

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.

SQLAlchemyでつまづいたことまとめ

Last updated at Posted at 2019-06-19

※加筆、追記していきます

環境

  • Python 3.7.3
  • SQLAlchemy1.3.3
  • MySQL 5.7.12

JOIN, OUTER JOINを使いたい

SQLAlchemy
session.query(
    Foo.id,
    Bar.name
).join(
    Bar,
    Foo.id == Bar.foo_id
)

ASを使いたい

SQL
SELECT name AS foo_name FROM foo
SQLAlchemy
session.query(
    (Foo.name).label('foo_name').all()
)

サブクエリを使いたい

SQLAlchemy
sub_query = session.query(
    Foo.id
).subquery('sub_query')

session.query(
    Bar.name,
    sub_query.c.id
).join(
    sub_query,
    Bar.id == sub_query.c.id,
).all()

selectで固定値をselectしたい

sql
SELECT id, true AS bar FROM foo
SQLAlchemy
from sqlalchemy.sql import expression

sub_query = session.query(
    Foo.id
).add_columns(
    expression.literal(True).label('bar')
).all()

5
3
1

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?