MYSQL多列索引
天蓬老师
天蓬老师 2017-04-17 11:36:12
0
2
665

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列上应该没法建立索引了吧,有没有其他办法优化呢

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
大家讲道理

1 For 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.

So:
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
You cannot use indexes, if:

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

2 Mysql does not have Function Based Indexes similar to Oracle, so you cannot use indexes here. The possible way is to build another related table, including (end_time-up.beg_time) as time field, and build the index. It is your own responsibility Updates between two tables (triggers or program logic)

巴扎黑

(end_time - beg_time) is calculated first when inserting. Try not to do this calculation when selecting.
I have the impression that using asc and desc at the same time cannot use the index.
Can be modified with logic, such as (beg_time - end_time) as time.
In this way, time is a negative value, and the sorting will be in the same direction.
order by score desc, time desc.
Finally, invert the time value in the program.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template