使用mySQL比较2个表

时间:2012-04-20 09:00:41

标签: mysql compare

我正在尝试比较2个mySQL表,以找出它们之间的差异。记录可以在TableA中找到,但不能在TableB中找到,反之亦然。

我的表格如下:

表A

Name    A1  A2  B1  B2
------------------------
John    11  12  21  23
John    11  12  21  22
John    33  34  31  33
Mary    41  42  54  55
Mary    71  72  81  82
Mary    41  42  51  52

表B

Name    A1  A2  B1  B2  C   D
---------------------------------
John    11  12  21  22  999 999
John    21  23  11  12  999 999
John    31  32  33  34  999 999
Mary    41  42  51  52  999 999
Mary    54  55  41  42  999 999

列A1和A2被视为一个组,B1和B2被视为另一个组。为了在两个表中都能找到记录,我需要

- TableA(A1,A2) = TableB(A1,A2) AND TableA(B1,B2) = TableB(B1,B2)

OR

- TableA(A1,A2) = TableB(B1,B2) AND TableA(B1,B2) = TableB(A1,A2)

对于上面的2个表格,我会将TableA的所有John与所有TableB的John以及TableA的所有Mary对比所有TableB的Mary进行比较。

我应该得到输出

Name    A1  A2  B1  B2  C   D
-----------------------------------------------
John    31  32  33  34  999 999 (from TableB)
Mary    41  42  54  55          (from TableA)
Mary    71  72  81  82          (from TableA)
Mary    54  55  41  42  999 999 (from TableB)

我是mySQL的新手,上面的内容对我来说似乎很复杂,我甚至不知道从哪里开始。

我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要发出两个查询:一个用于查找TableA中不存在TableB的记录,另一个用于相反情况。请注意,在一种情况下,它是LEFT JOIN,在第二种情况下,它是RIGHT JOIN

SELECT a.*, '' AS C, '' AS D, '(from TableA)' AS 'table'
FROM TableA AS a
LEFT JOIN TableB AS b
  ON ((a.A1 = b.A1 AND a.A2 = b.A2 AND a.B1 = b.B1 AND a.B2 = b.B2)
      OR (a.A1 = b.B1 AND a.A2 = b.B2 AND a.B1 = b.A1 AND a.B2 = b.A2))
    AND a.Name = b.Name
WHERE b.Name IS NULL

UNION

SELECT b.*, '(from TableB)' AS 'table'
FROM TableA AS a
RIGHT JOIN TableB AS b
  ON ((a.A1 = b.A1 AND a.A2 = b.A2 AND a.B1 = b.B1 AND a.B2 = b.B2)
      OR (a.A1 = b.B1 AND a.A2 = b.B2 AND a.B1 = b.A1 AND a.B2 = b.A2))
    AND a.Name = b.Name
WHERE a.Name IS NULL