mysql range索引,MySQL可以使用ORDER BY在RANGE QUERY中使用索引吗?

I have a MySQL table:

CREATE TABLE mytable (

id INT NOT NULL AUTO_INCREMENT,

other_id INT NOT NULL,

expiration_datetime DATETIME,

score INT,

PRIMARY KEY (id)

)

I need to run query in the form of:

SELECT * FROM mytable

WHERE other_id=1 AND expiration_datetime > NOW()

ORDER BY score LIMIT 10

If I add this index to mytable:

CREATE INDEX order_by_index

ON mytable ( other_id, expiration_datetime, score);

Would MySQL be able to use the entire order_by_index in the query above?

It seems like it should be able to, but then according to MySQL's documentation: "The index can also be used even if the ORDER BY does not match the index exactly, as long as all of the unused portions of the index and all the extra ORDER BY columns are constants in the WHERE clause."

The above passage seems to suggest that index would only be used in a constant query while mine is a range query.

Can anyone clarify if index would be used in this case? If not, any way I could force the use of index?

Thanks.

解决方案

MySQL will use the index to satisfy the where clause, and will use a filesort to order the results.

It can't use the index for the order by because you are not comparing expiration_datetime to a constant. Therefore, the rows being returned will not always all have a common prefix in the index, so the index can't be used for the sort.

For example, consider a sample set of 4 index records for your table:

a) [1,'2010-11-03 12:00',1]

b) [1,'2010-11-03 12:00',3]

c) [1,'2010-11-03 13:00',2]

d) [2,'2010-11-03 12:00',1]

If I run your query at 2010-11-03 11:00, it will return rows a,c,d which are not consecutive in the index. Thus MySQL needs to do the extra pass to sort the results and can't use an index in this case.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值