根据你的最佳选择是什么?

时间:2015-07-22 14:36:34

标签: sql sql-server-2008

根据你的最佳选择是什么?

select @MailTo=ISNULL((select data from filedata where descid=3104 and DataId=evt04) ,'') 
from event_21  
where evtid=@nFileId

select @MailTo=ISNULL(data ,'') 
from event_21  
innerjoin filedata  on event_21.evt04=filedata.dataid
where descid=3104   
and evtid=@nFileId

1 个答案:

答案 0 :(得分:1)

显然,“加入”比“内联选择查询”更快。我测试了1000行。你也可以测试一下。这是示例测试代码。

CREATE TABLE [dbo].[tableA](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_tableA] 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]

GO

CREATE TABLE [dbo].[tableB](
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Id] [int] NOT NULL,
    [Designation] [nvarchar](100) NULL,
 CONSTRAINT [PK_tableB] PRIMARY KEY CLUSTERED 
(
    [RowId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Declare  @Min       Int = 1
        ,@Max       Int = 1000

While (@Min <= @Max)
Begin
    Insert Into tableA(Name)
    Select  'Name would be the name of - ' + Cast(@Min As Nvarchar(10))

    Insert Into tableB(Id,Designation)
    Select   @Min
            ,'Desig could be the name of - Name' + Cast(@Min As Nvarchar(10))

    Select  @Min = @Min + 1
End

首先看@内联选择查询

-- inline query
Select   a.Id
        ,a.Name
        ,(Select Designation From tableB As b Where b.Id = a.Id) As Designation
From    tableA As a With (Nolock)

<强>输出:

enter image description here

执行计划:

enter image description here

现在加入查询: -

---- join 
Select   a.Id
        ,a.Name
        ,b.Designation
From    tableA As a With (Nolock)
        Join tableB As b On a.Id = b.Id

加入查询的执行计划: - enter image description here 你可以看到明显的区别。