mysql 索引 lt =,当同时使用> =和< =时如何索引MySQL表?

Let's say you have a query like,

select ID, REGION, START, END from COORD_SYSTEM

where REGION=? and TYPE=? and START >= ? and END <= ?;

And let's say this table has around 50,000 rows. The REGION column has 500 distinct values and the TYPE column has 50 distinct values. The ID column is the primary key.

What would be the best way to index the table? I'm not quite sure if one could achieve a covering index due to the >= and <= signs. Here are a few options:

create index on COORD_SYSTEM (REGION, TYPE)

create index on COORD_SYSTEM (REGION, TYPE, START)

create index on COORD_SYSTEM (REGION, TYPE, START, END)

Update - Here's the explain statement:

id: 1

select_type: SIMPLE

table: COORD_SYSTEM

type: range

possible_keys: indx_A

key: indx_A

key_len: 50

ref: NULL

rows: 590

Extra: Using where

1 row in set (0.00 sec)

解决方案

There's no reason that you can't use a covering index with range operators. The challenge (for non-covering indexes) is that the optimizer might think that a full scan might result in fewer page reads if your range is large, and the index won't be used for some of your queries. Similarly, for some parameter values, the optimizer may choose to do a full scan if the covering index isn't much better than a scan for some sets of parameters.

So, given the description in the question it's not actually possible to give the optimal solution for all cases.

What I tend to do with things like that is:

Create a copy of the database

Guess which index might do the job, and create that index.

EXPLAIN several queries with different sized ranges (more ranges need more I/O to get back to the table data if you haven't covered the query, so you should try for common range sizes and outliers)

Drop the index and try another, perhaps with a different covering index with the columns in a different order

You might even choose to create two or more covering indexes with the fields in different orders, assuming you run this query considerably more times than corresponding INSERTs or UPDATEs, and that the size of the index isn't a factor for disk space usage.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值