简体   繁体   中英

The ordering of indexes group

I read somewhere there is a different between these two indexes groups:

  • ADD KEY id_user (id_user,seen);
  • ADD KEY id_user (seen,id_user);

Well is there? If yes so their order should be based on what parameter?


In reality I have these two queries on one table:

Query1:

SELECT * FROM mytable WHERE id_user = :id AND seen IS NULL

Query2:

SELECT * FROM mytable WHERE id_user = :id AND timestamp > :tm

So what kind of indexes would be proper in my case? Currently I have three separated indexed on id_user , seen , timestamp columns.

Both your queries have an equality condition on id_user . Hence, either can take advantage of an index where id_user is the first key in the index. So, I would recommend the first index you mention.

MySQL has good documentation on multi-column indexes. I would suggest you start there to learn about them.

Your query can take advantage of indexes on (id_user, seen) and (id_user, timestamp) . Probably, the first key is most important. You should try this different indexes and see which best meet your performance goals.

Most likely, an index on user_id is enough. But if you have many repetitions of user_id s, then you can make two index groups

ADD KEY id_user1 (id_user, seen);
ADD KEY id_user2 (id_user, timestamp);

The select will first use user_id to reduce the number or matches, then the second field in the index, either timestamp or seen .

For a select that looks for user_id and seen , these two indexes

ADD KEY id_user1 (id_user,seen);
ADD KEY id_user2 (seen,id_user);

will have mostly the same result.

In any case, you should use EXPLAIN SELECT * FROM ... to check the execution of slow queries, so you can see exactly where it is slow, and if your indexes are actually used as expected.

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