2013-10-23 82 views
1

讓說,我有兩個表,需要MySQL密鑰索引?

的問題起見,我們假設他們是兩個表叫customerscars

Customers 
id name age 

Cars 
id customer_id brand_id engine cc 

我們是否需要索引customer_id?它有什麼優勢嗎?

+2

像往常一樣 - 「這取決於」。這取決於你的查詢。 –

回答

1

想強調一下InnoDB,索引自動在外鍵列上創建。 請參閱innodb-foreign-key-constraints

在您的情況下customer_id如果應用了外鍵約束。

1

是的,您可能想要加入customers表,您需要在customer_id上放置一個索引,以便查找速度更快。

但是就像在評論中說的那樣,如果你不打算加入customers表(或者做一個WHERE/GROUP BY/ORDER BY等等),並且純粹用它來顯示id,它不是純粹的。

1

根據應用程序的業務邏輯,以及如何將查詢的基礎上,其上CUSTOMER_ID的索引會給你一個巨大的優勢上查詢,如

select * from customers join cars on customer_id = customers.id -- list all customers with their associated cars 

甚至

select * from cars where customer_id = 2 -- list all cars for user 2 

更普遍,索引外鍵約束總是一個好主意。