我一直在使用 MySQL 和 sqlalchemy 来收集和存储数据。整个周末,我以大约 20,000 条推文/小时的速度收集推文,并将它们放在由推文 ID 索引的表 raw_tweets
中。我期待 ~1,000,000 行,但是当我运行时
SELECT COUNT(*) from raw_tweets;
查询只是挂起。我等了几分钟,还是没有。我对sql的了解相当有限。 table 上有可能有锁吗?这会导致它挂起而不会引起错误吗?我该如何诊断/解决这个问题?
附言看起来我对该表的所有查询都已挂起。
最佳答案
很可能它不会挂起,但需要很长时间才能执行。
如果表引擎是 InnoDB
,SELECT COUNT(*)
必须从表中读取所有行(以便对它们进行计数),如果数据库是在大量使用下,操作会花费大量时间。
这记录在 Limits on InnoDB Tables 中页:
InnoDB does not keep an internal count of rows in a table because concurrent transactions might “see” different numbers of rows at the same time. To process a
SELECT COUNT(*) FROM t
statement, InnoDB scans an index of the table, which takes some time if the index is not entirely in the buffer pool. To get a fast count, you have to use a counter table you create yourself and let your application update it according to the inserts and deletes it does. If an approximate row count is sufficient,SHOW TABLE STATUS
can be used.
如上所述,如果一个大概的行数对您来说足够了,那么运行:
SHOW TABLE STATUS WHERE NAME = 'raw_tweets'
并查看结果的 Rows
列。
请注意:
SHOW TABLE STATUS
返回的行数是近似值;它可能与实际值相差几个百分点(表格较小时差异较大);SHOW TABLE STATUS
返回的值在每次后续运行时都会发生变化,即使表上没有写入事件也是如此。
关于MySQL 查询卡在 `SELECT COUNT(*)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36842350/