2014-09-10 50 views
0

我的存儲過程具有以下查詢。有什麼方法可以將聯合換成一個查詢或其他方式來優化它。如何在sql server中替換存儲過程中的union

Select col1,col2 
from logs lg 
inner join EmployeeType_1 et1 on et1.empID=lg.userID 
where lg.usertype=1 

Union 

Select col1,col2 
from logs lg 
inner join EmployeeType_2 et2 on et2.empID=lg.userID 
where lg.usertype=2 

Union 

Select col1,col2 
from logs lg 
inner join EmployeeType_3 et3 on et13.empID=lg.userID 
where lg.usertype not in (1,2) 
+0

來自日誌和col2的col1是et1.empID | et2.empID |基於表的et3.empID。 – 2014-09-10 15:50:27

回答

2

據推測,col1col2來自logs。這裏有一種方法:

Select col1,col2 
from logs lg 
where (lg.usertype = 1 and exists (select from EmployeeType_1 et1 where et1.empID = lg.userID)) and 
     (lg.usertype = 2 and exists (select from EmployeeType_2 et1 where et1.empID = lg.userID)) and 
     (lg.usertype not in (1, 2) and exists (select from EmployeeType_3 et1 where et1.empID = lg.userID)) 
+0

感謝您的回覆。但嵌套選擇查詢可能會增加整個查詢的執行時間。比聯盟好嗎? – 2014-09-10 18:43:05

+0

@ManishMawatwal。 。 。它可能比'union'更好,因爲它不必刪除重複項。 – 2014-09-11 04:17:57

0

一個LEFT JOIN應該做的伎倆:

SELECT 
    lg.col1, 
    Coalesce(et1.empID, et2.empID, et3.empID) As col2 
FROM 
    logs As lg 
    LEFT JOIN EmployeeType_1 As et1 
    ON et1.empID = lg.userID And lg.usertype = 1 
    LEFT JOIN EmployeeType_2 As et2 
    ON et2.empID = lg.userID And lg.usertype = 2 
    LEFT JOIN EmployeeType_3 As et3 
    ON et3.empID = lg.userID And lg.usertype Not In (1, 2) 

然而,因爲你的例子只是從三個EmployeeType_X表檢索empID列,該列始終等於logs表中的userID列,則不需要加入表格:

SELECT 
    lg.col1, 
    lg.userID As col2 
FROM 
    logs As lg