MySQL 分页性能有限制

问题描述 投票:0回答:1

听说MySql分页(限制x,y)性能不太好。如果转到某些最后页面,它仍然会完全扫描所有以前的记录(在磁盘上)。 解决方案之一是获取上一条记录的 ID,然后使用 where 进行过滤(其中 id > previous ID Limit 0, 20 )。但如果SQL中包含group up和sum,这个方法就不起作用了,因为sum的个数是错误的。 有人有解决办法吗? 我知道如果你想要更好的性能,你就不会使用mysql。但我还是想知道有没有办法优化它。

例如:

select productID, locationID, sum(qty), create_date from inventory
where create_date between 'yyyy-mm-dd' and 'yyyy-mm-dd'
group by locationID, productID
order by productID
limit 100, 20;

它仍会扫描磁盘上的前 100 条记录。

mysql limit
1个回答
0
投票

您可以考虑添加以下covering索引:

CREATE INDEX idx2 ON inventory (create_date, productID, locationID, qty);

此索引(如果使用)应让 MySQL 丢弃任何超出

create_date
值范围的记录。 之后,MySQL 可以扫描整个索引并按
GROUP BY
子句中的 2 列进行聚合。 该索引包含这 2 个聚合列以及
qty

© www.soinside.com 2019 - 2024. All rights reserved.