TSQL效率 - INNER JOIN由EXISTS取代

时间:2015-02-21 23:19:22

标签: tsql

可以重写以下内容以提高效率吗? 如果我不需要EXISTS中的字段,我会使用country,但我确实需要这些字段,并且不确定如何编写这些字段以提高效率。

SELECT      distinct 
        p.ProvinceID,
        p.Abbv as RegionCode,
        p.name as RegionName,
        cn.Code as CountryCode,
        cn.Name as CountryName
 FROM         dbo.provinces AS p 

                  INNER JOIN dbo.Countries AS cn ON p.CountryID = cn.CountryID
                  INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID
                  INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID

WHERE l.IsActive = 1 AND l.IsApproved = 1 

2 个答案:

答案 0 :(得分:1)

有两点需要注意:

  1. 您加入dbo.Listings会导致许多记录,因此您需要使用DISTINCT(通常是一个昂贵的运营商)

  2. 对于列不在选择中的任何表格,您可以移至EXISTS(但查询计划程序无论如何都会有效地为您执行此操作)

  3. 所以试试这个:

    SELECT       
            p.ProvinceID,
            p.Abbv as RegionCode,
            p.name as RegionName,
            cn.Code as CountryCode,
            cn.Name as CountryName
     FROM  dbo.provinces AS p 
           INNER JOIN 
           dbo.Countries AS cn 
           ON p.CountryID = cn.CountryID
     WHERE EXISTS (SELECT 1 FROM 
                   dbo.Listings l 
                   INNER JOIN dbo.Cities c 
                   on l.CityID = c.CityID
                   WHERE  c.ProvinceID = p.ProvinceID
                   AND l.IsActive = 1 AND l.IsApproved = 1 
                  )
    

    检查之前和之后的查询计划 - 无论如何,查询计划程序可能足够智能,但您删除了distinct

答案 1 :(得分:-1)

通过为优化程序提供更多有用信息,以下内容通常会更好:

SELECT       
        p.ProvinceID,
        p.Abbv as RegionCode,
        p.name as RegionName,
        cn.Code as CountryCode,
        cn.Name as CountryName
 FROM  dbo.provinces AS p 
       INNER JOIN 
       dbo.Countries AS cn 
       ON p.CountryID = cn.CountryID
      INNER JOIN (
        SELECT
            p.ProvinceID
        FROM  
           dbo.Listings l 
           INNER JOIN dbo.Cities c 
           on l.CityID = c.CityID
           WHERE l.IsActive = 1 AND l.IsApproved = 1 
        GROUP BY
            p.ProvinceID
      ) list
    on list.ProvinceID = p.ProvinceID