优化SQL SERVER中的LEFT JOIN

时间:2016-09-08 18:58:16

标签: sql-server tsql

SELECT h.*
FROM  h
 LEFT JOIN  au ON au.ID = h.Key AND au.RaID = 40190 AND h.EntityType = 'Detail'
 LEFT JOIN  ip ON ip.ID = h.Key AND ip.RaID = 40190 AND h.EntityType = 'itempart'
WHERE 
coalesce(au.id,ip.id) is not null

任何人都知道如何优化这个? h是巨大的历史记录表。

1 个答案:

答案 0 :(得分:2)

如果在允许的类型上使用union,那么可以使用内部联接:

SELECT h.*
FROM  h
    INNER JOIN (
                SELECT ID, 'Detail' AS EntityType FROM au WHERE (RaID = 40190)
                UNION ALL
                SELECT ID, 'itempart' AS EntityType FROM ip WHERE (RaID = 40190)
            ) AS filt
            ON h.Key = filt.ID
            AND h.EntityType = filt.EntityType

还要确保您的过滤/加入列上有索引。并且在查找性能问题时一如既往地检查查询计划,如上面n8wrl所示。