在尝试提高极慢查询的速度时(在两个表上只有几万分钟,在SQL Server 2008上只有几万行,如果重要的话),我将问题缩小到OR我的内连接中,如:
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.MainTable AS mt
INNER JOIN dbo.OtherTable AS ot ON ot.ParentID = mt.ID
OR ot.ID = mt.ParentID
Run Code Online (Sandbox Code Playgroud)
我把它更改为(我希望是)一对等效的左连接,如下所示:
SELECT mt.ID, mt.ParentID,
CASE WHEN ot1.MasterID IS NOT NULL THEN
ot1.MasterID ELSE
ot2.MasterID END AS MasterID
FROM dbo.MainTable AS mt
LEFT JOIN dbo.OtherTable AS ot1 ON ot1.ParentID = mt.ID
LEFT JOIN dbo.OtherTable AS ot2 ON ot2.ID = mt.ParentID
WHERE ot1.MasterID IS NOT NULL OR ot2.MasterID IS NOT NULL
Run Code Online (Sandbox Code Playgroud)
..现在查询运行大约一秒钟!
OR加入条件通常是个坏主意吗?或者我在桌子的布局中不知何故不幸?