There is no problem not worth solving, and no technology not worth learning!

In MySQL 8.0, when querying the total number of table records, the analysis optimization of the timeout

一个接口请求响应超时,原因在于 count(*) SQL 耗时 54 秒。表中数据量超过 1000万 条

1. An interface request response timeout, because count(*) SQL takes 54 seconds. The amount of data in the table exceeds 10 million. as shown in Figure 1

一个接口请求响应超时,原因在于 count(*) SQL 耗时 54 秒。表中数据量超过 1000万 条
Figure 1

SELECT
	count(*) AS AGGREGATE 
FROM
	`tables`


2. The table field Shipping_Type has an index to add, and its value is only 1 and 2 possibilities. Decide to add the where condition Shipping_Type in (1,2). The query time is 3 seconds. as shown in Figure 2

其中表字段 shipping_type 有添加索引,且其值仅有 1、2 两种可能。决定添加 where 条件 shipping_type IN (1,2)。查询时长 3 秒
Figure 2

SELECT
	count(*) AS AGGREGATE 
FROM
	`tables` 
WHERE
	shipping_type IN (
	1,
	2)


3. The final decision is based on the primary key ID as the WHERE condition, in order to maintain the uniformity of the WHERE conditions of all count sql. Add WHERE ID > 0 when a COUNT SQL does not exist where condition exists. It took 4 seconds, in line with expectations. as shown in Figure 3

最终决定基于主键 ID 作为 where 条件,以尽量保持所有 count SQL 的 where 条件的统一。当一条 count SQL 没有 where 条件存在时,就添加 WHERE id > 0。耗时 4 秒,符合预期
Figure 3

Need long-term technical maintenance or remote troubleshooting?

I am a PHP / Go backend engineer with 15+ years of experience, focused on existing system maintenance, bug fixing, performance optimization, server troubleshooting, WordPress maintenance, and small feature iterations.

If your project is facing any of the following issues, we can start with a small troubleshooting task first:

  • ✅ PHP / Laravel / Yii2 legacy systems without active maintenance
  • ✅ Go / Gin backend APIs that need troubleshooting or optimization
  • ✅ Slow, broken, or unstable WordPress websites
  • ✅ Nginx / MySQL / Redis / Linux server issues
  • ✅ CDN / Cloudflare / DNS / HTTPS configuration problems
  • ✅ Long-term remote technical support or part-time maintenance

More details: About Me & Collaboration

WeChat: 13980074657
Email: shuijingwanwq@gmail.com
Telegram: @shuijingwan
GitHub: https://github.com/shuijingwan

评论

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.