从表

时间:2017-03-06 18:52:04

标签: sql sql-server join

我有4张桌子 表1
UserId(PK)----------用户名
1 ------------------ ABC
2 ------------------- PQR

表2
CUSTID(PK)---------的CustName
1 ----------------------- Cust1
2 ----------------------- Cust2
3 ----------------------- Cust3

表3
CUSTID(FK)----------用户ID(FK)
1个----------------------- 1
2 ----------------------- 2

表4
OfficeId(PK)---------- OfficeName -------- CUSTID(FK)
1 ------------------------关闭1 ------------------- 1个
2 ------------------------关闭2 ------------------- 1个
3 ------------------------ Off3 ------------------- 2

Tabl5
OfficeId(FK)----------用户ID
1个------------------------- 1
3 ------------------------- 2

问题是当User与3 Cust相关联,但是他被分配了只属于2个Cust的办公室,那么它应该返回未分配的officeId吗? 从上表,
当我将UserId = 1传递给我的存储过程时 我想要关注输出

OfficeId --------- OfficeName
2 -----------------关闭2

2 个答案:

答案 0 :(得分:2)

SELECT OfficeId, OfficeName
FROM Table4
WHERE OfficeId NOT IN (
    SELECT Table4.OfficeId
    FROM Table3
    INNER JOIN Table4
        ON Table3.CustId = Table4.CustId
    INNER JOIN Tabl5
        ON Tabl5.UserId = Tabl3.UserId
        AND Tabl5.OfficeId = Table4.OfficeId
);

答案 1 :(得分:2)

我不想跟踪哪些表是哪个,所以我使用更有意义的表名(对我而言)......

使用not exists()

select o.OfficeId, o.OfficeName
from users_customers uc
  inner join office o
    on uc.CustId = o.CustId
where uc.UserId = @UserId
  and not exists (
    select 1
    from users_office uo
    where uo.UserId = @UserId
      and uo.OfficeId = o.OfficeId
  )

使用except(这也会删除重复的结果)

select o.OfficeId, o.OfficeName
from users_customers uc
  inner join office o
    on uc.CustId = o.CustId
where uc.UserId = @UserId

except

select o.OfficeId, o.OfficeName
from users_office uo
  inner join office o 
    on uo.OfficeId = o.OfficeId
where uo.UserId = @UserId