简体   繁体   中英

MySql Indexs for where and order by clause

I'm having problems with big table indexs.

I have the table (id,external_item_id,time_stamp,status_id);

What's the best index for this 3 queries:

 SELECT *
 FROM items pi
 WHERE 1=1 AND external_item_id IN (1154,1155,1163,3660,6801,98)
 ORDER BY pi.time_stamp DESC, pi.id DESC
 LIMIT 12


 SELECT *
 FROM items pi
 WHERE 1=1 AND external_item_id IN (1154,1155,1163,3660,6801,98) AND status_id < 20
 ORDER BY pi.time_stamp DESC, pi.id DESC
 LIMIT 12

 SELECT *
 FROM items pi
 WHERE 1=1 AND external_item_id IN (1154,1155,1163,3660,6801,98) AND pi.time_stamp <= 13434534452 AND id < 1600
 ORDER BY pi.time_stamp DESC, pi.id DESC
 LIMIT 12

Because of the list of items for the in , it is hard to optimize this query.

There are basically two approaches the engine can take for these queries. Use the index for the where clause. Then either do the sort or use the index for the oder by . Because there are inequalities in the where ( in is an "inequality"), the index cannot be directly used for the where .

The best indexes for the where are: items(external_item_id, status_id) and items(external_item_id, time_stamp) .

An alternative execution plan is to use the index for the order by and then filter on the fly. This suggests trying: items(time_stamp, id, external_item_id, status_id) . The last two columns are so the index can satisfy the where without going to the original data.

None of these are perfect solutions.

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