Why is SQLAlchemy count() much slower than the raw query?

后端 未结 3 711
广开言路
广开言路 2020-12-12 17:11

I\'m using SQLAlchemy with a MySQL database and I\'d like to count the rows in a table (roughly 300k). The SQLAlchemy count function takes about 50 times as long to run as w

3条回答
  •  情书的邮戳
    2020-12-12 17:56

    The reason is that SQLAlchemy's count() is counting the results of a subquery which is still doing the full amount of work to retrieve the rows you are counting. This behavior is agnostic of the underlying database; it isn't a problem with MySQL.

    The SQLAlchemy docs explain how to issue a count without a subquery by importing func from sqlalchemy.

    session.query(func.count(User.id)).scalar()
    
    >>>SELECT count(users.id) AS count_1 \nFROM users')
    

提交回复
热议问题