简体   繁体   English

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

[英]Declare table and join it shows slow, but fast when using real number

I've try following SQL and it was slow when I useing declare @NewCityJudge table and join it, but it was fast when I convert table into real number and join it. 我尝试按照SQL进行操作,使用声明@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

But it faster when using 但是使用时速度更快

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)

The @NewCityJudge always less 5 records. @NewCityJudge总是少于5条记录。

The first way takes 5 seconds, The second way takes 500 ms. 第一种方法需要5秒钟,第二种方法需要500毫秒。

Thanks 谢谢

PS. PS。 It was fast when using #NewCityJudge temp table, but I afraid it cause some transaction issue 使用#NewCityJudge临时表时速度很快,但我担心它会导致某些事务问题

在此处输入图片说明

As opposed to a Join, you could use the following: 与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)

Anytime you use TOP (#) on a table with some joins, it is less than ideal. 每当您在具有某些联接的表上使用TOP(#)时,它都不理想。 I would also like to understand why TOP (300) ? 我也想了解为什么选择TOP(300)? Is this for testing purposes ? 这是出于测试目的吗? How many records are in MyTable ? MyTable中有多少条记录? If you remove TOP (300), you may find your query time issue resolved. 如果删除TOP(300),则可能会解决查询时间问题。

I solved this problem by using temp table instead of parameter. 我通过使用临时表而不是参数解决了这个问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM