0

尝试对具有相同数据布局的 2 个表进行比较,并且在同一行上有不匹配的记录

Table1                   Table2
------                   ------

CUSTOMER PART            CUSTOMER  PART

CUSTID1  PART1           CUSTID1  PART1
CUSTID1  PART2           CUSTID1  PART2
CUSTID1  PART3           CUSTID1  PART3
CUSTUD1  PART4


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  PART3
CUSTID1  PART2           CUSTID1  PART1
CUSTID1  PART3           CUSTID1  PART2
CUSTUD1  PART4           NULL     NULL
4

2 回答 2

1

您需要执行以下操作:

SELECT T1.CUSTID, T1.PART, T2.CUSTID, T2.PART 
FROM TABLE1 AS T1 
     INNER JOIN TABLE2 AS T2 ON T1.CUSTID = T2.CUSTID 
WHERE T1.PART <> T2.PaRT

没有必要使用左外连接。order by 子句对 join 的结果没有任何影响;它只是命令结果。

于 2012-10-26T17:55:35.647 回答
0

您当前的查询,即使是样本数据,也应该为您提供大量数据:

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。

于 2012-10-26T21:05:36.350 回答