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

后端 未结 3 703
广开言路
广开言路 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:48

    It took me a long time to find this as the solution to my problem. I was getting the following error:

    sqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 126 (HY000): Incorrect key file for table '/tmp/#sql_40ab_0.MYI'; try to repair it

    The problem was resolved when I changed this:

    query = session.query(rumorClass).filter(rumorClass.exchangeDataState == state)
    return query.count()
    

    to this:

    query = session.query(func.count(rumorClass.id)).filter(rumorClass.exchangeDataState == state)
    return query.scalar()
    

提交回复
热议问题