MySql - 索引自然唯一的列有什么好处吗?

MySql - Is there any benefit to indexing a column that is naturally unique?

我们以lastName为例。

假设您的数据库中没有重复的姓氏(偶然,不是因为 unique),索引此 lastName 列会有任何好处吗?

用于搜索的查询类似于 SELECT * IN t WHERE lastName='Smith'

如果列中的每个条目都是唯一的,那么索引如何起作用?难道它不必搜索每个条目吗?

抱歉,我刚刚开始学习索引,我真的很想更好地理解它。

谢谢。

是的,即使列值是唯一的,索引也有好处。在索引中,值不仅是唯一的,而且还以树结构组织,使您可以搜索具有 O(log N) 复杂度的行。

维基百科上有一篇关于它的很棒的文章:Database Index

... The data is present in arbitrary order, but the logical ordering is specified by the index. The data rows may be spread throughout the table regardless of the value of the indexed column or expression. The non-clustered index tree contains the index keys in sorted order, with the leaf level of the index containing the pointer to the record (page and the row number in the data page in page-organized engines; row offset in file-organized engines).

In a non-clustered index

The physical order of the rows is not the same as the index order. The indexed columns are typically non-primary key columns used in JOIN, WHERE, and ORDER BY clauses. There can be more than one non-clustered index on a database table. ... Consider the following SQL statement: SELECT first_name FROM people WHERE last_name = 'Smith'; To process this statement without an index the database software must look at the last_name column on every row in the table (this is known as a full table scan). With an index the database simply follows the B-tree data structure until the Smith entry has been found; this is much less computationally expensive than a full table scan.

一般来说,列中的唯一值越多,或者它的基数越高 What is cardinality in MySQL?,该列上的索引就越有用。