A. Count () in SQLAlchemy
COUNT () Statistics are particularly slow:
Session.query (CLS). Count () 8W data cost nearly 50s
However, query directly in the database: SELECT COUNT (*) from TABLE_NAME. Spents only 0.738s
This difference makes people really strange.
Later in "1" saw the reason: The count()
method is used to determine how many rows are returned in the result set, let us look at the resulting SQL statement, SQLAlchemy First Take out all the rows that meet the criteria , and then count the number of SELECT count(*)
rows.
This is after iterating through all the database records, then select COUNT (*). It's scary, when the data is large, less than 100W is not big. Of course time is all spent on traversing the top.
We can func.count()
use the Count function directly from an expression. -----This is the equivalent of the direct count () in the database
Session.query (Func.count (cls.id)). Scalar ()---Direct statistics primary key ID
Second, other optimization
-------2016-6-28 11:40:23---
Source: "1" sqlalchemy query
SQLAlchemy optimization count () ...