2014-02-20 126 views
0

我希望簡化這一令人困惑的左外通過可能使用其中語句轉換左外連接到WHERE語句

Select approved.orderId 
From (select distinct orderId from OrderLine where isApproved = 1 and isDismissed = 0) approved 
     left outer join 
     (select distinct orderId from OrderLine where isApproved = 0 and isDismissed = 0) unapproved 
     on approved.orderId = unapproved.orderId 
Where unapproved.orderId Is Null 

喜歡的東西連接語句到的東西更容易閱讀:

Select orderId 
From (select distinct orderId from OrderLine where (isApproved = 1 and isDismissed = 0) OR (isApproved = 0 and isDismissed = 0 and orderId is null)) 

回答

1

這應該做的:

SELECT DISTINCT O.orderId 
FROM OrderLine O 
WHERE O.isDismissed = 0 
AND O.isApproved = 1 
AND NOT EXISTS(SELECT 1 FROM OrderLine 
       WHERE isApproved = 0 
       AND isDismissed = 0 
       AND orderId = O.OrderId) 
0

它看起來像連接試圖獲得至少有e批准的生產線但沒有未經批准的生產線。這應該等同於

select distinct orderId 
from OrderLine 
where isApproved = 1 
    and isDismissed = 0 
    AND orderID NOT IN 
     (select orderId 
     from OrderLine 
     where isApproved = 0 
     and isDismissed = 0) 
0

except應該蠻快的工作,你的用例,並刪除需要兩個連接查詢和內部查詢:

SELECT DISTINCT orderId 
FROM orderline 
WHERE isApproved = 1 and isDismissed = 0 
EXCEPT 
SELECT orderId 
FROM orderline 
WHERE isApproved = 0 and isDismissed = 0