例如,我有下表:
table Product
------------
id
category_id
processed
product_name
此表在 id
category_id
和 processed
和 (category_id, processed)
列上有索引。这张表的统计是:
select count(*) from Product; -- 50M records
select count(*) from Product where category_id=10; -- 1M records
select count(*) from Product where processed=1; -- 30M records
我想查询的最简单的查询是:(select * 是必须的)。
select * from Product
where category_id=10 and processed=1
order by id ASC LIMIT 100
上面没有限制的查询只有大约10,000条记录。
我想多次调用上述查询。每次我出去时,我都会将字段 processed
更新为 0。(因此它不会出现在下一个查询中)。当我测试真实数据时,有时优化器会尝试使用 id
作为键,因此会花费很多时间。
如何优化上述查询(一般而言)
P/S:为了避免混淆,我知道最好的索引应该是(category, processed, id)。但我无法更改索引。我的问题只与优化查询有关。
谢谢
最佳答案
对于这个查询:
select *
from Product
where category_id = 10 and processed = 1
order by id asc
limit 100;
最佳索引在 product(category_id, processed, id)
上。这是具有三部分键的单个索引,键按此顺序排列。
关于mysql - SQL:使用索引优化大表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188810/