素材牛VIP会员
MYSQL多列索引
 贝***0  分类:SQL代码  人气:785  回帖:2  发布于6年前 收藏

1.首先提个问题,假设有这样的sql查询:
select * from TABLEA....order by score desc,time asc
我想在score和time上建立多列索引,但是score是降序,time是升序,如果建立默认的索引都是升序的,那查询的时候还能走这个索引么?应该有办法建立符合相应排序的索引吧?

2.上述的time字段,其实是下表中(end_time - beg_time)这两个字段相减的值,即sql语句为:
select total_score as score,(end_time-beg_time) as time from TABLEA ....order by score desc,time asc
请问这样的话time列上应该没法建立索引了吧,有没有其他办法优化呢

 标签:索引mysql

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv5 码农
黑***黑 Web前端工程师 6年前#1

(end_time - beg_time)在insert的时候就先计算出来啊,尽量select的时候不做这种计算。
印象中同时使用asc和desc不能使用索引。
可以用逻辑修改,比如(beg_time - end_time) as time。
这样time就是一个负值,再取排序就同方向了。
order by score desc,time desc。
最后在程序里把time值取反。

Lv6 码匠
飞***猪 交互设计师 6年前#2

1 对mysql来说, :
http://dev.mysql.com/doc/refman/5.7/en/create-index.html

An index_col_name specification can end with ASC or DESC. These
keywords are permitted for future extensions for specifying ascending
or descending index value storage. Currently, they are parsed but
ignored; index values are always stored in ascending order.

所以:
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
你不能用到索引, if:

You mix ASC and DESC:
SELECT * FROM t1 ORDER BY key_part1 DESC,key_part2 ASC;

2 mysql没有 类似Oracle里的Function Based Indexes, 所以你这里没法用到索引. 可能的办法是 另外建一个 关联表, 包含(end_time-up.beg_time) as time 字段, 建索引. 自己负责两个表之间的 更新(触发器 或者程序逻辑)

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取