您当前的查询,即使是样本数据,也应该为您提供大量数据:
SELECT T1.CUSTID, T1.PART, T2.CUSTID, T2.PART FROM TABLE1 AS T1
LEFT JOIN TABLE2 AS T2 ON T1.CUSTID = T2.CUSTID
WHERE T1.PART <> T2.PaRT
ORDER BY T1.CUSTID
预期结果:
CUSTID1 PART1 CUSTID1 PART2
CUSTID1 PART1 CUSTID1 PART3
CUSTID1 PART2 CUSTID1 PART1
CUSTID1 PART2 CUSTID1 PART3
CUSTID1 PART3 CUSTID1 PART1
CUSTID1 PART3 CUSTID1 PART2
CUSTID1 PART4 CUSTID1 PART1
CUSTID1 PART4 CUSTID1 PART2
CUSTID1 PART4 CUSTID1 PART3
您可能想要一个 FULL OUTER JOIN 条件ON T1.CustID = T2.CustID AND T1.Part = T2.Part
。如果你不能做 FULL,请使用 LEFT 和 RIGHT 连接的 UNION。或者,如果您不担心 Table2 中的行在 Table1 中没有对应的行,那么您现有的带有增强 ON 子句的 LEFT JOIN 就可以了。
如果你想要所有匹配的行和所有不匹配的行,那么你使用
SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
如果您只想查看不匹配的行,请编写:
SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
WHERE T1.Part IS NULL OR T2.Part IS NULL
LEFT-UNION-RIGHT 查询(针对所有行)可能是:
SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
FROM Table1 AS T1
LEFT OUTER JOIN Table2 AS T2
ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
UNION
SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
FROM Table1 AS T1
RIGHT OUTER JOIN Table2 AS T2
ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
并且对所有行的 LEFT 唯一查询可能是:
SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
FROM Table1 AS T1
LEFT OUTER JOIN Table2 AS T2
ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
如果您只想查看不匹配的行,则可以添加适当的 WHERE 过滤条件。(显然,如果您只想查看匹配的行,则使用常规的 INNER JOIN 或仅 JOIN。)
告诫 Emptor:没有 DBMS 验证过这个 SQL。