简体   繁体   中英

Indexes on foreign key in MySQL

I have simple code.

CREATE TABLE foo (

client_id int,
order_id int,

PRIMARY KEY (client_id, order_id),
INDEX (order_id),

FOREIGN KEY (client_id) REFERENCES baz(id),
FOREIGN KEY (order_id) REFERENCES bar(id)

);

I know that MySQL will automatic add index to column with primary key, but what if I have complex primary key? (example in my code). Why I must add index to second column in primary key? I think that MySQL will automatic add index only for first column but to second, third ... I must add this constraint manually? Is any answer in official documentation?

you can refer to the link http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

if any table has a multi-column index for eg: (col1, col2, col3) , then you can have the search capabilities for (col1) , (col1, col2) , and (col1, col2, col3)

This index will never be used if the search do not form a Left most prefix on the index, which in this case is col1

So you need to have col1 as prefix and a search with col2,col3 wont use the index

You might need a different index for the same, so you will have to index col2 separately

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