如何进一步优化此查询?

时间:2013-08-21 15:38:45

标签: sql sql-server-2008

我正在尝试优化此查询。对于如何使估算的执行计划中的估计子树成本降低成本,我有点难过。结果通常平均返回50k行,并且需要比我想要的更长的时间。任何时候剃光都会有用。感谢。

SELECT
    tbl1.DID AS "CID",
    tbl1.ID AS "ID",

    tbl2.Column2 AS "Col2",
    tbl2.Column3 AS "Col3",

    tbl3.Column4 AS "Col4",
    tbl3.Column5 AS "Col5",

    tbl4.Column6 AS "Col6"
FROM TABLE1 tbl1 WITH (NOLOCK)
INNER JOIN TABLE2 tbl2 WITH (NOLOCK) ON tbl1.ID = tbl2.CID
INNER JOIN TABLE3 tbl3 WITH (NOLOCK) ON tbl1.ID = tbl3.CID 
INNER JOIN TABLE4 tbl4 WITH (NOLOCK) ON tbl1.DID = tbl4.CID

更新 - 主要密钥信息。每个表的内部联接中的所有列都已具有索引。如果一个主键,那么它看起来像下面的那个,否则它是一个非群集,如底部的那个: 主键索引如下所示。

ALTER TABLE [dbo].[IDX_TABLE1] ADD  CONSTRAINT [PK_TABLE1] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,      IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON  [PRIMARY]

非群集的其他列索引如下所示:

CREATE NONCLUSTERED INDEX [IDX_TABLE1] ON [dbo].[TABLE1] 
(
[DID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON,    ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

表定义:

CREATE TABLE [dbo].[TABLE1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[DID] [int] NULL
CONSTRAINT [PK_TABLE1] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]



CREATE TABLE [dbo].[TABLE2](
[CID] [int] NOT NULL,
[Column3] [varchar](50) NULL,

 CONSTRAINT [PK_TABLE2] PRIMARY KEY CLUSTERED 
(
[CID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,   ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]



CREATE TABLE [dbo].[TABLE3](
[CID] [int] NOT NULL,
[Column4] [varchar](50) NULL
    [Column5] [varchar](50) NULL
CONSTRAINT [PK_TABLE3] PRIMARY KEY CLUSTERED 
(
[CID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]



CREATE TABLE [dbo].[TABLE4](
[CID] [int] NOT NULL,
[Column6] [char](2) NULL
CONSTRAINT [PK_TABLE4] PRIMARY KEY CLUSTERED 
(
[CID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,   ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

2 个答案:

答案 0 :(得分:4)

确保每个表的连接列都有一个索引。在SQL Server中,您还可以使用INCLUDE选项创建“覆盖索引”,并将查询中使用的所有列放在那里。这样只会读取索引,并且查询永远不会进入数据表。

像这样:

create index idx_name
on tbl2 (cid)
include (Column2, Column3)

根据附加信息,您需要tbl2上的索引和tbl3上与上述类似的索引。

create index idx_name1
on tbl3 (cid)
include (Column4, Column5)

这应该有助于一些人的表现。

答案 1 :(得分:2)

根据您提供的信息,解决此问题的正确方法是选择整个查询,右键单击该选择,然后选择“在数据库引擎优化顾问中分析查询”。它将为您提供有关如何优化它的一些想法。

如果没有对架构,执行计划,当前运行时的重要知识,我们无法对此进行优化。我们还需要了解它正在运行的硬件。

一般而言,调优顾问会让您深入了解可以对底层架构进行哪些更改以产生更快的结果。它还会告诉你应该看到多少改进(例如98%)。