2017-03-06 83 views
2

存在的記錄我有4個表
表1
用戶ID(PK)----------用戶名
1 ----------- ------- ABC
2 ------------------- PQRSQL查詢來獲得不從表

表2
CUSTID(PK)-------- - 客戶名稱
1 -----------------------客戶1
2 ------------------ ----- Cust2
3 ----------------------- Cust3

表3
CustId(FK)---------- UserId(FK)
1 ----------------------- 1
2 ----------------------- 2

表4
OfficeId(PK)---------- OfficeName -------- CustId(Fk)
1 ------------------------ Off1 ---------- --------- 1
2 ------------------------ Off2 ------------ ------- 1
3 ------------------------ Off3 -------------- ----- 2

Tabl5
OfficeId(FK)---------- UserId
1 ------------------------- 1
3 ------------------------- 2

問題是當用戶與3 Cust關聯時,但他被分配了屬於只有2個Cust,那麼它應該返回未分配的officeId? 從上面的表,
當我通過用戶ID = 1到我的存儲過程
欲以下輸出

OfficeId --------- OfficeName
2 --------- --------關閉2

回答

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 
+0

:謝謝哥們..它適合我。 – Kida

+0

@Kida樂意幫忙! – SqlZim

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 
); 
+0

感謝您的幫助。 – Kida