sqlalchemy使用count()函數遇到的問題sql
在使用flask-sqlalchemy對一個千萬級別表進行count操做時,出現了耗時嚴重、內存飆升的問題。flask
原代碼:session
# 統計當日登錄次數 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
進行了一次子查詢,會生成臨時表,效率低。優化
優化代碼:spa
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打印:scala
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)
無子查詢,效率高。code