SQL:使用索引优化对大表的查询

Trầ*_* Dự 0 mysql sql mariadb

例如,我有下表:

table Product
------------
id
category_id 
processed
product_name
Run Code Online (Sandbox Code Playgroud)

该表在列id category_idprocessed和和上有索引(category_id, proccessed)。该表的统计数据为:

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
Run Code Online (Sandbox Code Playgroud)

我要查询的最简单查询是:(必须选择 *)。

select * from Product 
where category_id=10 and processed=1 
order by id ASC LIMIT 100  
Run Code Online (Sandbox Code Playgroud)

上面的无限制查询只有大约 10,000 条记录。

我想多次调用上述查询。每次我出去时,我都会将字段更新processed为 0。(因此它不会出现在下一个查询中)。当我对真实数据进行测试时,有时优化器会尝试将其id用作密钥,因此会花费大量时间。

如何优化上述查询(一般而言)

P/S:为了避免混淆,我知道最好的索引应该是(类别、已处理、ID)。但我无法更改索引。我的问题仅与优化查询有关。

谢谢

Gor*_*off 5

对于此查询:

select *
from Product
where category_id = 10 and processed = 1
order by id asc
limit 100;
Run Code Online (Sandbox Code Playgroud)

最佳索引位于product(category_id, processed, id)。这是一个具有三部分键的单个索引,键按此顺序排列。

  • @TrầnKimDự如果您无法更改索引,那么您期望如何提高性能? (4认同)