zoukankan      html  css  js  c++  java
  • [Flask]sqlalchemy使用count()函数遇到的问题

    sqlalchemy使用count()函数遇到的问题

    在使用flask-sqlalchemy对一个千万级别表进行count操作时,出现了耗时严重、内存飙升的问题。

    原代码:

    # 统计当日登陆次数
    count = LoginLog.query.filter(LoginLog.username == username, LoginLog.status == 0, db.cast(LoginLog.time, db.DATE) == db.cast(datetime.utcnow(), db.DATE)).count()

    sql打印:

    SELECT
        count(*) AS count_1
    FROM
        (
            SELECT
                loginlog.id AS loginlog_id,
                loginlog.username AS loginlog_username,
                loginlog.time AS loginlog_time,
                loginlog. STATUS AS loginlog_status
            FROM
                loginlog
            WHERE
                loginlog.username = % (username_1) s
            AND loginlog. STATUS = % (status_1) s
            AND CAST(loginlog.time AS DATE) = CAST(%(param_1) s AS DATE)
        ) AS anon_1

    进行了一次子查询,会生成临时表,效率低。

    优化代码:

    count = db.session.query(func.count(LoginLog.id)).filter(LoginLog.username == username, LoginLog.status == 0, db.cast(LoginLog.time, db.DATE) == db.cast(datetime.utcnow(), db.DATE)).scalar()

    sql打印:

    SELECT
        count(loginlog.id) AS count_1
    FROM
        loginlog
    WHERE
        loginlog.username = % (username_1) s
    AND loginlog. STATUS = % (status_1) s
    AND CAST(loginlog.time AS DATE) = CAST(%(param_1) s AS DATE)

    无子查询,效率高。

  • 相关阅读:
    Linux的学习--系统目录
    PHP内核的学习--创建PHP扩展
    PHP的学习--连接MySQL的三种方式
    MIME Type
    颜色的命名
    JavaScript的学习--生成二维码
    MySQL的学习--触发器
    Google Guava之--cache
    java代码调用oracle存储过程
    oracle序列
  • 原文地址:https://www.cnblogs.com/ttkl/p/11095227.html
Copyright © 2011-2022 走看看