2017-05-16 81 views
1

我有一個表像下面SQL查詢的結果顯示使用的記錄設置

商品

enter image description here

現在我有另一個名爲表

工作表

enter image description here

而且還有一個多對多的關係BW工作列表和商品

Worklist_commodities

enter image description here

現在我想所有未排除的商品,但如果商品是使用在工作清單中,它也被標記爲排除,那麼我也想在結果集中加載結果。

那麼加載結果的最終查詢是什麼。問題可以通過工會輕鬆解決,但我不使用聯合,因爲我使用了某種不具有聯合功能的ORM。

SQL UNION查詢我用來獲取結果集,我想會得到相同的結果,而不UNION

`SELECT this_.ID as ID, 
     this_.Name AS Name, 
     this_.ParentID AS ParentID, 
     this_.IsExcluded AS IsExcluded 
     FROM INFO_Commodities this_ WHERE this_.IsExcluded = 0 
    UNION 
    SELECT this_.ID as ID, 
     this_.Name AS Name, 
     this_.ParentID AS ParentID, 
     this_.IsExcluded AS IsExcluded 
     FROM INFO_Commodities this_ WHERE this_.IsExcluded = 1 AND this_.ID IN 
    (SELECT wc.[CommodityID] 
    FROM SWF_WorkLists as w INNER JOIN SWF_WorkListCommodities AS wc on w.ID 
    = wc.WorklistID WHERE wc.[CommodityID] = this_. ID) 

`

+1

添加一些示例表格數據和預期結果 - 以及格式化文本。 – jarlh

+0

您使用的是Oracle還是MS SQL Server?不要標記不涉及的產品。 – jarlh

+0

我正在使用MS SQL Server –

回答

1

您可以使用FULL JOIN(我的例子是UNION ALL,但可以更換1=0A.ID = B.ID AND A.Name=B.Nama AND ...

WITH A AS(
    SELECT this_.ID as ID, 
    this_.Name AS Name, 
    this_.ParentID AS ParentID, 
    this_.IsExcluded AS IsExcluded 
    FROM INFO_Commodities this_ WHERE this_.IsExcluded = 0 
), B AS (
    SELECT this_.ID as ID, 
    this_.Name AS Name, 
    this_.ParentID AS ParentID, 
    this_.IsExcluded AS IsExcluded 
    FROM INFO_Commodities this_ WHERE this_.IsExcluded = 1 AND this_.ID IN 
    (SELECT wc.[CommodityID] 
    FROM SWF_WorkLists as w INNER JOIN SWF_WorkListCommodities AS wc on w.ID 
    = wc.WorklistID WHERE wc.[CommodityID] = this_. ID) 
) 
SELECT 
    ID  = COALESCE(A.ID, B.ID), 
    Name = COALESCE(A.Name, B.Name) 
FROM A 
FULL JOIN B ON 1 = 0