查询左连接OR效率低

时间:2016-10-07 16:19:52

标签: sql sql-server

我有一个表(200K行),其中包含一个名为" Campaign"的字段。我有一个单独的活动表列表,其中包含其他信息。我想加入where (campaign_id = campaign) OR (cid.spend_source = a.Traffic_Source AND a.Campaign = cid.Campaign_Name)

我面临的问题是OR语句会导致效率下降,导致嵌套循环有4亿行。

什么是更好的方法?

UPDATE a
SET    a.campaign_name = cid.Campaign_Name,
       a.Campaign_ID = cid.Campaign_ID
FROM   database.dbo.table a
       LEFT JOIN carb.dbo.carb_lookup_campaignid cid
              ON cid.Campaign_ID = a.Campaign
                  OR ( cid.spend_source = a.Traffic_Source
                       AND a.Campaign = cid.Campaign_Name ) 

3 个答案:

答案 0 :(得分:1)

做两个单独的left join s:

UPDATE a
    SET a.campaign_name = coalesce(cidss.Campaign_Name, cidlc.Campaign_Name),
        a.Campaign_ID = coalesce(cidss.Campaign_ID, cidlc.Campaign_ID)
    FROM database.dbo.table a LEFT JOIN
         carb.dbo.carb_lookup_campaignid cidss
         ON cidss.Campaign_ID = a.Campaign and
            cidss.spend_source = a.Traffic_Source LEFT JOIN
         carb.dbo.carb_lookup_campaignid cidlc
         ON cidlc.Campaign_ID = a.Campaign and
            cidlc.Campaign_Name = a.Campaign and
            cidss.Campaign_ID is null
     WHERE cidss.Campaign_ID is not null or cidls.Campaign_ID is not null;

每个人LEFT JOIN都可以利用相应的索引(Campaign_ID, spend_source)(Campaign_ID, Campaign_Name)

答案 1 :(得分:1)

嗨,从其他表格更新时始终使用 MERGE 语句>您可以使用以下查询

MERGE INTO a
USING 
(SELECT * FROM a
 LEFT OUTER JOIN carb_lookup_campaignid cid
ON (ON cid.Campaign_ID = a.Campaign)
OR ( cid.spend_source = a.Traffic_Source
                       AND a.Campaign = cid.Campaign_Name )
)
WHEN MATCHED
THEN
UPDATE 
SET
a.campaign_name = cid.Campaign_Name,
a.Campaign_ID = cid.Campaign_ID

答案 2 :(得分:1)

使用两个单独的更新

  UPDATE a
  SET    a.campaign_name = cid.Campaign_Name,
         a.Campaign_ID = cid.Campaign_ID
  FROM   database.dbo.table a
  LEFT JOIN carb.dbo.carb_lookup_campaignid cid              
          ON cid.Campaign_ID = a.Campaign
  ;

  UPDATE a
  SET    a.campaign_name = cid.Campaign_Name,
         a.Campaign_ID = cid.Campaign_ID
  FROM   database.dbo.table a
  LEFT JOIN carb.dbo.carb_lookup_campaignid cid               
              ON ( cid.spend_source = a.Traffic_Source
                   AND a.Campaign = cid.Campaign_Name ) 
  ;