使用存在的SQL查询

时间:2018-04-22 20:21:16

标签: sql-server

我正在尝试使用Exists或Not Exists从两个表中查找值,任一选项就足够了。

这两个表是工人和作业,我正在尝试找到未分配给546号楼的工人的名字。问题是工人被分配到多个建筑物,因此在一个例子中,工人被分配到546和423,所以他们不应该在回报中表现出来,但他们确实如此。

表工作者:

Worker_ID | Worker_name
     1411 | Beth 
     1521 | Amber 
     1351 | Caren 
     1345 | Mike 
     1456 | Austin 
     1457 | Steven 
     1744 | Sam 

表格分配:

Worker_ID | Building_Num
     1411 | 546
     1521 | 423
     1351 | 423
     1345 | 431
     1456 | 421
     1457 | 465
     1744 | 423
     1411 | 423
     1521 | 451
     1351 | 428
     1345 | 421
     1456 | 427
     1457 | 426
     1744 | 546

我尝试了以下内容:

SELECT W.Worker_NAME, B.BLDG_ID
FROM W_WORKER W INNER JOIN A_ASSIGNMENT A ON W.WORKER_ID = A.WORKER_ID 
                INNER JOIN B_BUILDING B ON B.BLDG_ID = A.BLDG_ID
WHERE EXISTS ( SELECT  DISTINCT W.WORKER_ID
              FROM W_WORKER W INNER JOIN A_ASSIGNMENT A ON W.WORKER_ID = A.WORKER_ID
              WHERE A.BLDG_ID <> 435) 

有效的嵌套查询示例:

SELECT W.Worker_NAME
    FROM W_WORKER W INNER JOIN A_ASSIGNMENT A ON W.WORKER_ID = A.WORKER_ID 
                    INNER JOIN B_BUILDING B ON B.BLDG_ID = A.BLDG_ID
    WHERE B.BLDG_ID <> ( SELECT  DISTINCT B.BLDG_ID 
                  FROM W_WORKER W INNER JOIN A_ASSIGNMENT A ON W.WORKER_ID = A.WORKER_ID 
                                  INNER JOIN B_BUILDING B ON B.BLDG_ID = A.BLDG_ID
                  WHERE B.BLDG_ID = 546)

2 个答案:

答案 0 :(得分:0)

使用EXCEPT是一种更好,更快的选择。

skiprows=1

你基本上以这种方式消除了建筑546的工人。

(对不起格式化手机)

答案 1 :(得分:0)

NOT EXISTS

select *
from workers w
where
not exists (   -- if a worker is also assigned to building 546 then don't return
select 1 from 
assignment a
where
a.worker_id = w.worker_id   -- this will match all assignments for a worker
and building_num = 546    -- but if there is at least an assignment to building 546 then exclude the worker

)