如何优化这个复杂的 MySql 查询
How To Optimize This Complex MySql Query
我有这个问题
SELECT id, number, count, name FROM temp AS t1 WHERE (SELECT COUNT(*)
FROM temp AS t2
WHERE t2.number = t1.number AND t2.count > t1.count
) = 0 AND id NOT IN (SELECT id FROM temp WHERE count < 3)
它当前执行时间太长,table temp 有 150 000 行并且还在增加。
我是 运行 这个来自 php (mysqli)。我怎样才能提高性能?
在您的查询条件
AND id NOT IN (SELECT id FROM temp WHERE count < 3)
可以用作
and `count` < 3
你也可以使用exists
策略转换子查询,最后添加一些索引。
https://dev.mysql.com/doc/refman/5.5/en/subquery-optimization-with-exists.html
select id,number,`count`,name from temp t1
where t1.`count` < 3
and not exists(
select 1 from temp t2
where t2.number = t1.number AND t2.count > t1.count
)
索引可能需要,如果还没有,因为
alter table temp add index cnt_idx(`count`);
alter table temp add index number_idx(`number`);
确保在应用索引之前对 table 进行备份。
您可以随时使用 explain select
检查查询运行状况。
我有这个问题
SELECT id, number, count, name FROM temp AS t1 WHERE (SELECT COUNT(*)
FROM temp AS t2
WHERE t2.number = t1.number AND t2.count > t1.count
) = 0 AND id NOT IN (SELECT id FROM temp WHERE count < 3)
它当前执行时间太长,table temp 有 150 000 行并且还在增加。
我是 运行 这个来自 php (mysqli)。我怎样才能提高性能?
在您的查询条件
AND id NOT IN (SELECT id FROM temp WHERE count < 3)
可以用作
and `count` < 3
你也可以使用exists
策略转换子查询,最后添加一些索引。
https://dev.mysql.com/doc/refman/5.5/en/subquery-optimization-with-exists.html
select id,number,`count`,name from temp t1
where t1.`count` < 3
and not exists(
select 1 from temp t2
where t2.number = t1.number AND t2.count > t1.count
)
索引可能需要,如果还没有,因为
alter table temp add index cnt_idx(`count`);
alter table temp add index number_idx(`number`);
确保在应用索引之前对 table 进行备份。
您可以随时使用 explain select
检查查询运行状况。