这些是我的表格:
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
由于
答案 0 :(得分:1)
SELECT
C.Supplier1
FROM Customer C
LEFT JOIN Supplier S
ON C.Supplier1 = S.supplier_id
WHERE S.user_id IS NULL
答案 1 :(得分:0)
您的问题是Customer表未规范化,即您在customer表中有重复的供应商列。您可以两次加入供应商表。 e.g。
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))
这可能更容易用作缺少supplier2缺失的供应商1的并集。