sqlalchemy in查询与聚合查询

in查询

db.query(UserAccount #模型名称).filter(account_type.in_(['1','2','3'])).all()

array_agg 聚合查询

db.query(func.min(UserAccount.username) # 去重,
         func.array_agg(UserAccount.account_id) # 聚合) \
            .filter(UserAccount.deleted == False,
                    UserAccount.account_type == account_type) \
            .group_by(UserAccount.username) \
            .all()

原始数据

username account_id
18331946590 1559641515
18331946590 1590949087
18331946590 1639294033
18331946590 1599305910

查询结果示例

username account_id
18331946590 1559641515,1590949087,1639294033,1599305910

注意

filter_by 和filter的区别
filter_by 不能使用范围查询,如in,这不需要带上模型名称,直接使用字段名字
filter 查询时需要带上模型名称

posted @ 2023-03-08 18:17  蒲公英PGY  阅读(457)  评论(0编辑  收藏  举报