我怎么能优化这个查询?

时间:2010-10-16 00:11:36

标签: sql sql-server-2008

UPDATE a
SET CountOfAA=dt.CountOf,
CountOfBB=dt.CountOf
FROM @MediaResurce  a
INNER JOIN (SELECT 
                aa.Sku,ISNULL(COUNT(bb.sku),0) AS CountOf
                FROM @MediaResurce                      aa
                    LEFT OUTER JOIN @MediaResurce_Pics  bb 
                    ON aa.sku=bb.sku
                WHERE somecol = 0
                GROUP BY aa.Sku
           ) dt ON a.sku=dt.sku
INNER JOIN (SELECT 
                aa.Sku,ISNULL(COUNT(bb.sku),0) AS CountOf
                FROM @MediaResurce                      aa
                    LEFT OUTER JOIN @MediaResurce_Pics  bb 
                    ON aa.sku=bb.sku
                 WHERE somecol = 1
                GROUP BY aa.Sku
           ) dt2 ON a.sku=dt2.sku

2 个答案:

答案 0 :(得分:3)

提供的内容有点抽象,难以提供反馈。

UPDATE a
   SET CountOfAA = CASE WHEN b.somecol = 0 THEN b.CountOf END,
       CountOfBB = CASE WHEN b.somecol = 1 THEN b.CountOf END
  FROM @MediaResurce a
  JOIN (SELECT aa.Sku,
               somecol,
               ISNULL(COUNT(bb.sku), 0) AS CountOf
          FROM @MediaResurce aa
     LEFT JOIN @MediaResurce_Pics bb ON aa.sku = bb.sku
         WHERE somecol IN (0, 1)
      GROUP BY aa.Sku, somecol) b ON b.sku = a.sku

答案 1 :(得分:0)

刚开始从头开始写作,结果与OMG的答案类似:

UPDATE a
SET CountOfAA=dt.CountOfAA,
    CountOfBB=dt.CountOfBB
FROM @MediaResurce a
INNER JOIN (
    SELECT
        aa.sku,
        SUM(CASE WHEN aa.somecol = 0 THEN 1 ELSE 0 END) AS CountOfAA,
        SUM(CASE WHEN aa.somecol = 1 THEN 1 ELSE 0 END) AS CountOfBB
    FROM @MediaResurce_Pics bb 
    INNER JOIN @MediaResurce aa ON aa.sku = bb.sku
    GROUP BY aa.sku
) dt ON dt.sku = a.sku

关注点:

  • 我认为'somecol'在@MediaResurce中。如果它存在于@MediaResurce_Pics中,我认为没有理由第二个INNER JOIN
  • 对于较大的表,通过在源表上设置适当的索引,例如在'sku'和'somecol'上,可以显着提高对此类查询的速度。但表变量不支持索引。你能把它们改成临时表还是固定表?这张桌有多大?