2013-10-23 83 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 

更普遍,索引外键约束总是一个好主意。