SQL查询以在结果集中显示已使用的记录

时间:2017-05-16 10:53:53

标签: sql sql-server sql-server-2012

我有一张如下表

日用品

enter image description here

现在我有另一个名为

的表

工作清单

enter image description here

b.w工作清单和商品有很多关系

Worklist_commodities

enter image description here

现在我想获得所有未被排除的商品,但如果商品在工作清单中使用并且它也被标记为排除,那么我也想将结果加载到结果集中。

那么加载结果的最终查询是什么。工会很容易解决这个问题,但是我没有使用工会,因为我使用了某种没有工会功能的ORM。

SQL UNION QUERY我以前得到的结果集我希望在没有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 个答案:

答案 0 :(得分:1)

您可以使用FULL JOIN(我的示例适用于UNION ALL,但您可以将1=0替换为A.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