簡體   English   中英

聚集索引與復合索引。 哪一個更好?

[英]Clustered index vs composite index. Which one is better?

我正在使用 Microsoft SQL Server 2017。我有一個名為 ProductMapping 的表。 下面是表結構:

CREATE TABLE [dbo].[Accommodation_ProductMapping](
    [ProductMappingId] [uniqueidentifier] NOT NULL,
    [AccommodationId] [uniqueidentifier] NULL,
    [SupplierId] [uniqueidentifier] NULL,
    [SupplierId] [varchar](50) NULL,
    [SupplierName] [varchar](50) NULL,
    [SupplierProductReference] [nvarchar](255) NULL,
    [ProductName] [nvarchar](500) NULL,
    [CountryName] [nvarchar](255) NULL,
    [CountryCode] [nvarchar](50) NULL,
    [CityName] [nvarchar](255) NULL,
    [CityCode] [nvarchar](100) NULL
)

這個表有150億條數據。 我在這個表上創建了非集群和復合索引。 以下是詳細信息:-

CREATE NONCLUSTERED INDEX [IDX_CityCode] ON [dbo].[ProductMapping]
(
    [CityCode] ASC
)

CREATE NONCLUSTERED INDEX [IDX_CountryCode] ON [dbo].[ProductMapping]
(
    [CountryCode] ASC,
)

CREATE NONCLUSTERED INDEX [IDX_CountryCityCode] ON [dbo].[ProductMapping]
(
    [CountryCode] ASC,
    [CityCode] ASC
)

CREATE NONCLUSTERED INDEX [IDX_ProductCountryCityCode] ON [dbo].[ProductMapping]
(
    [ProductName] ASC,
    [CountryCode] ASC,
    [CityCode] ASC
)

CREATE NONCLUSTERED INDEX [IDX_AccommodationCountryCityCode] ON [dbo].[ProductMapping]
(
    [AccommodationId] ASC,
    [CountryCode] ASC,
    [CityCode] ASC
)

我能夠毫無問題地獲取數據。

我只想知道我上面創建的是否有任何未使用或冗余的索引?

此外,我已經在國家和城市代碼上創建了一個復合索引“IDX_CountryCityCode”,所以我是否需要一個單獨的非集群索引“CityCode”和“CountryCode”(例如 IDX_CityCode 和 IDX_CountryCode)。

先感謝您。

已編輯

我只想知道我是否刪除了上述所有索引(即[IDX_CityCode], [IDX_CountryCode], [IDX_CountryCityCode], [IDX_ProductCountryCityCode] & [IDX_AccommodationCountryCityCode] )並將它們全部放在一個復合索引中,如下所示。 這會起作用還是最好的方法?

CREATE NONCLUSTERED INDEX [IDX_CityCountryAccommodationProduct] ON [dbo].[ProductMapping]
(
    [CityCode] ASC,
    [CountryCode] ASC,
    [AccommodationId] ASC,
    [ProductName] ASC
)

你的問題很廣泛。 這個答案的目的是讓您了解您提出的問題,因為這個問題似乎並不廣泛——只是兩個不同選項之間的二元選擇。

創建索引是為了優化查詢(以及強制執行唯一約束,但這是另一回事)。

您尚未顯示任何查詢,因此無法確定哪組索引是最佳的。 但是,它們並不等效。

例如,您的復合索引可用於以下where子句:

where CityCode = @CityCode
where CityCode = @CityCode and CountryCode = @CountryCode
where CityCode = @CityCode and CountryCode = @CountryCode and AccommodationId = @AccommodationId
where CityCode = @CityCode and CountryCode = @CountryCode and AccommodationId = @AccommodationId and ProductName = @ProductName

重要的是列按索引中定義的順序使用(而不是它們在where子句中出現的順序。

如果@CityId不存在,則無法使用此索引。 所以,這個指數不適合:

where CountryCode = @CountryCode
where CountryCode = @CountryCode and AccommodationId = @AccommodationId
whereCountryCode = @CountryCode and AccommodationId = @AccommodationId and ProductName = @ProductName

有了四個索引,可以使用其中之一 當可以使用多個索引時,優化器會嘗試使用“最佳”索引。 有時,優化器不會選擇最好的。

您的問題的標題是關於聚集索引與非聚集索引。 這帶來了其他問題——特別是如何插入和更新數據。 聚集索引對數據的存儲方式施加了限制,因此它們會對數據修改的性能產生重大影響。

索引還有很多細微差別。 但是,從根本上說,它們不是由數據結構驅動,而是由查詢驅動(盡管在某些情況下,例如規范化數據模型,很明顯需要某些類型的查詢)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM