本文記錄幾種與 SELECT DISTINCT 相同作用的 SQLAlchemy 寫法。

本文環境

  • Python 3.6.5
  • SQLAlchemy 1.3.4

範例 Model

以下為本文的範例 model - User

from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    username = Column(String)
    password = Column(String)


engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session() 

使用 distinct()

找出不重複的 User.name:

q = session.query(User.name).distinct()
for r in q.all():
    print(r)

上述 SQL 語句為:

SELECT DISTINCT user.name AS user_name FROM user

又或者以下的寫法也是一樣的效果:

from sqlalchemy import distinct


q = session.query(distinct(User.name).label('uniq_username'))
for r in q.all():
    print(r)

上述 SQL 語句為:

SELECT DISTINCT user.name AS uniq_username FROM user

如果要同時 DISTINCT 多個欄位:

q = session.query(User.name, User.id).distinct()
for r in q.all():
    print(r)

其 SQL 語句為:

SELECT DISTINCT user.name AS user_name, user.id AS user_id FROM user

如果是想計算不重複的個數,則可以加上 func.count() 幫忙:

from sqlalchemy import func
from sqlalchemy import distinct

session.query(func.count(distinct(User.name)))

使用 group_by()

除了使用 distinct() 之外,也可以用 group_by() 達到相同作用:

q = session.query(User.name).group_by(User.name)
for r in q.all():
    print(r)

其 SQL 語句為:

SELECT user.name AS user_name FROM user GROUP BY user.name

GROUP BY 多個欄位範例:

q = session.query(User.name, User.id).group_by(User.name, User.id)
for r in q.all():
    print(r)

其 SQL 語句為:

SELECT user.name AS user_name, user.id AS user_id FROM user GROUP BY user.name, user.id

References

https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.distinct