在python sqlalchemy中子查询的使用

来源:互联网 发布:java封装 编辑:程序博客网 时间:2024/05/17 01:00

query = select([machine_products_table.c.id, /
                    machine_products_table.c.machine_id.label("kiosk"), /
                   machine_products_table.c.sale_price.label("sale_price"), /
                   machine_products_table.c.quantity.label("quantity"), /
                   select([func.min(machine_stock_events_table.c.action_time)], /
                          and_(machine_stock_events_table.c.machine_id==machine_products_table.c.machine_id, /
                               machine_stock_events_table.c.product_id==productId)).as_scalar().label("load_days"), /
                   select([func.max(machine_transactions_table.c.trs_time)], /
                          and_(machine_transactions_table.c.machine_id==machine_products_table.c.machine_id, /
                               machine_transactions_table.c.product_id==productId, /
                               machine_transactions_table.c.state == "closed")).as_scalar().label("no_transaction_days")/
                   ], /
                   and_(machine_products_table.c.machine_id.in_(select([machines_table.c.machine_id], /
                                                                       machines_table.c.client_id==clientId).as_scalar()), /
                        machine_products_table.c.product_id==productId, /
                        machine_products_table.c.quantity != 0))
       
    if sortKey:
        if str(sortOrder).lower() == "desc":
            query = query.order_by(sortKey.desc())
        else:
            query = query.order_by(sortKey)
    if limit:
        query = query.limit(limit)
    if offset:
        query = query.offset(offset)
    tmp = meta.Session.execute(query).fetchall()
    result = []
    for t in tmp:
        load_days = '--'
        no_transaction_days = '--'
        if t[4]:
            load_days = getDaySpan(str(t[4]),getCurTime())
        if t[5]:
            no_transaction_days = getDaySpan(str(t[5]),getCurTime())
        result.append((t[0], t[1], t[2], t[3], load_days, no_transaction_days))