MYSQL多列索引
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列上应该没法建立索引了吧,有没有其他办法优化呢
Answers
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; i ndex 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 字段, 建索引. 自己负责两个表之间的 更新(触发器 或者程序逻辑)