唯一索引列顺序——重要吗?

Unique index column order - is it important?

关于索引列顺序的文章很多,我明白了。但是,我发现 none 关于唯一索引。

简单示例:ProductCategory table 使用 ProductCategoryMapping table 和 3 列具有 n-n 关系:标识 IdProductIdCategoryId.

如果我创建一个包含 2 列的唯一索引 UN_ProductCategoryMapping_ProductProductIdCategoryId,我是否还应该以相反的顺序创建另一个唯一索引,假设我有时想 "list all products of a category",有时 "list all categories a product belongs to"?

SQL 服务器是否足够智能以在这种情况下进行优化?

唯一性 不依赖于列顺序。如果您声明第 1、2 和 3 列的组合是唯一的,而其他人声明第 2、1 和 3 列的组合是唯一的,那么您在陈述相同的事实。

但这并不是说所有索引都是平等的,或者同样有用。索引只有在您可以使用它们的所有 left-most 列时(可能)才有用。如果您有一个不使用任何索引的 left-most 列的查询,满足该查询的唯一方法是扫描整个 table.