简体   繁体   中英

Issue with MySQL Compound Primary Key

I am having an issue with a table the uses a compound primary key. The key consists of a date followed by an bigint.

Selects on the table look to be scanning even when only selecting fields from the PK and using a where clause that contains both columns. For Example

SELECT mydate, myid from foo WHERE mydate >='2014-08-26' AND my_id = 1234;

Explain select shows using where and the number of rows considered is in the millions.

One oddity is the key_len which is shown as 7 which seems far too small.

My instinct says the key is broken but I may be missing something obvious.

Any thoughts?

Thank you

Richard

For this query, the index you want is on id, date :

 create index idx_foo_myid_mydate on foo(my_id, mydate);

This is because the conditions in the where clause have an equality and inequality. The equality conditions need to match the index from left to right, before the inequalities can be applied.

MySQL documentation actually does a good job (in my opinion) in explaining composite indexes.

Your existing index will be used for the inequality on mydate . However, all the index after the date in question will then be scanned to satisfy the condition on my_id . With the right index, MySQL can just go to the right rows directly.

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