0

这些是我的表:

Customer Table
--------------
CUST_ID
SUPPLIER1
SUPPLIER2

Supplier Table
--------------
SUPPLIER_ID
USERID

User Table
----------
USER_ID

规则:

客户可以有多个供应商,但如果他们有客户,供应商必须在用户表中。

因为所有供应商都必须是用户,所以我需要找到用户表中缺少的所有已使用或分配的供应商。

这个查询让我得到所有不是用户的供应商

SELECT 
    U.*
FROM 
    USER U
LEFT JOIN 
    SUPPLIER S ON S.USER_ID = U.USER_ID
WHERE 
    S.USER_ID IS NULL

但是我如何获得所有不是用户的客户供应商?

我试过这个,但它似乎不正确:

SELECT 
    *
FROM 
    USER U
LEFT JOIN 
    (SELECT C.SUPPLIER1, S.USER_ID FROM CUSTOMER C, SUPPLIER S WHERE 
     C.SUPPLIER1 = S.SUPPLIER_ID AND C.SUPPLIER1 IS NOT NULL) 
    S2 ON S2.USER_ID = U.USER_ID
WHERE 
    S2.USER_ID IS NULL

谢谢

4

2 回答 2

1
SELECT
C.Supplier1
FROM Customer C
LEFT JOIN Supplier S
ON C.Supplier1 = S.supplier_id

WHERE S.user_id IS NULL
于 2013-09-10T17:36:05.167 回答
0

您的问题是客户表未规范化,即您在客户表中有重复的供应商列。您可以加入供应商表两次。例如

select C.Supplier1, U1.UserID, C1.Supplier2, U2.UserID
from Customer C
left join Supplier S1 on (S1.Supplier_id = C.Supplier1)
left join User U1 on (U1.UserID = C.Supplier1)
left join Supplier S2 on (SS.Supplier_id = C.Supplier2)
left join User U2 on (U2.UserID = C.Supplier2)
where 
   ((not C1.Supplier1 is null) and (U1.UserID is null))
or ((not C2.Supplier1 is null) and (U2.UserID is null))

这很容易用作缺少供应商 1 和缺少供应商 2 的联合。

于 2013-09-10T17:47:11.393 回答