简体   繁体   中英

optimizing Mysql tables with index

SELECT * 
FROM sms_report 
WHERE R_uid = '159' 
  AND R_show = '1' 
ORDER BY R_timestamp DESC , R_numbers

This is my query. Now it is using filesort i need to add index so that its optimized. Below is the output of explain

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra

1   SIMPLE  sms_report  ref     R_uid,R_show    R_uid   4   const   765993  Using where; Using filesort

The table is MYISAM and i have created indexes on R_smppid, R_uid, R_show, R_timedate, R_numbers

Someone adviced me on adding composite index. can you tell me which all fields should I index and how.

Try using a composite index on R_uid,R_show,R_timestamp,R_numbers - that way it should be able to find exactly the rows you are looking for in 1 index, and have the results already sorted.

EDIT - DESC may throw that optimization... but it may be worth a try

Since MySQL says possible keys == R_uid,R_show , try creating a composite index over just those two.

Try running ANALYZE TABLE sms_report; Maybe also OPTIMIZE TABLE

Also try using EXPLAIN EXTENDED ... to see if it gives you more info.

If you are only interested in some of the columns, only specify those columns instead of * . Some databases (I don't know if MySQL is one of them) can skip reading the table and return the results straight from the index if the index includes all the columns you're interested in. eg if you're only interested in R_uid and R_show, then doing SELECT R_uid, R_show FROM ... instead of SELECT * FROM ... could speed things up. (Again, I don't know if this applies to MySQL.)

How to add index:

alter table sms_report add index new_index (uid, show, R_timestamp, R_numbers);

How to force query to use new index

SELECT * 
FROM sms_report 
USE INDEX new_index
WHERE R_uid=159 AND R_show=1
ORDER BY R_timestamp DESC, R_numbers;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM