1. Reference: Analysis and optimization of timeouts when querying total table record counts in MySQL 8.0. When a count SQL does not have a where clause, add WHERE id > 0.
2. Reference: How to check if table is already has a where clause in Laravel Query Builder? The final implementation is as follows
PHP
if (empty($builder->getQuery()->wheres)) {
$builder->where('id', '>', 0);
}
3. The final generated SQL is as follows, which meets expectations
SQL
select count(*) as aggregate from `tables` where `id` > 0
