欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python - SQLAlchemy 子查询

程序员文章站 2022-03-11 19:01:59
...

Python - SQLAlchemy 子查询

Max.Bai

2020-08

1. 子查询需要先执行subquery

2. 子查询的列需要通过c来访问  比如: sub_query.c.alarm

    base_sub_query = (
        db.query(
            AlarmRule.alarm,
            AlarmRule.condition,
            AlarmRule.compare_float
        )
        .filter(
            AlarmRule.alarm == Alarm.id,
            Alarm.module == MonitorModule.id,
            AlarmRule.is_valid == 1,
            AlarmRule.enable == 1,
        )
        .order_by(
            AlarmRule.alarm,
            AlarmRule.condition,
        )
        .having(1 == 1)
    )


    sub_query = (
        base_sub_query.filter(AlarmRule.condition == "LT")
        .order_by(AlarmRule.compare_float)
        .subquery()
    )

    query = db.query(sub_query).group_by(
        sub_query.c.alarm,
        sub_query.c.condition,
    )
    
    result = [d._asdict() for d in query.all()]