声明表并加入它显示慢,但使用实数时快

时间:2016-05-03 10:51:35

标签: sql sql-server

我尝试使用SQL,当我使用declare @NewCityJudge表并加入它时速度很慢,但是当我将表转换为实数并加入它时速度很快。

-- input id into @NewCityJudge, only one record
declare @NewCityJudge table(CountryId int)
insert into @NewCityJudge 
select CountryId from .... 


SELECT TOP (300) *
MyTable as b
    join ComponentLanguageIndex as c on c.id = b.[key]
    join ComponentCountryTags e on c.ComponentId = e.ComponentId
    join @NewCityJudge  as d on d.CountryId = e.CountryId -- join @NewCityJudge here

但使用

时速度更快
SELECT TOP (300) *
MyTable  as b
    join ComponentLanguageIndex as c on c.id = b.[key]
    join ComponentCountryTags e on c.ComponentId = e.ComponentId
where CountryId in (39)

@NewCityJudge总是少于5条记录。

第一种方式需要5秒钟, 第二种方式需要500毫秒。

由于

PS。使用#NewCityJudge临时表时速度很快,但我担心它会导致一些交易问题

enter image description here

2 个答案:

答案 0 :(得分:0)

与Join相反,您可以使用以下内容:

SELECT TOP (300) *
MyTable  as b
    join ComponentLanguageIndex as c on c.id = b.[key]
    join ComponentCountryTags e on c.ComponentId = e.ComponentId
where e.CountryId IN (Select CountryId from @NewCityJudge)

任何时候你在带有一些连接的表上使用TOP(#),它都不太理想。我还想了解为什么TOP(300)?这是用于测试目的吗? MyTable中有多少条记录?如果您删除TOP(300),您可能会发现您的查询时间问题已解决。

答案 1 :(得分:0)

我通过使用临时表而不是参数解决了这个问题。

Create table  #NewCityJudge(CountryId int) insert into #NewCityJudge  select CountryId from .... 


SELECT TOP (300) * MyTable as b
    join ComponentLanguageIndex as c on c.id = b.[key]
    join ComponentCountryTags e on c.ComponentId = e.ComponentId
    join #NewCityJudge  as d on d.CountryId = e.CountryId