簡體   English   中英

SQL查詢從表中獲取不存在的記錄

[英]Sql query to get not exist records from table

我有4張桌子
表格1
UserId(PK)---------- UserName
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 ------------------------關閉3 ------------------- 2

Tabl5
OfficeId(FK)----------用戶ID
1 ------------------------- 1
3 ------------------------- 2

問題是,當用戶與3個Cust關聯時,但他被分配的辦公室僅屬於2個Cust,那么它應該返回未分配的officeId? 在上面的表格中
當我將UserId = 1傳遞給存儲過程時
我想要以下輸出

OfficeId --------- OfficeName
2 -----------------關閉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
);

我不想跟蹤哪個表是哪個表,所以我使用的表名對我來說更有意義。

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM