Rayne
Rayne

Reputation: 14977

Using mySQL to compare 2 tables

I'm trying to compare 2 mySQL tables to find differences between them. A record may be found in TableA but not in TableB, or vice versa.

My tables are as follows:

TableA

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

TableB

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

Columns A1 and A2 is considered a group, and B1 and B2 considered another group. For a record to be considered found in both tables, I need

- 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)

For the 2 tables, above, I would compare all of TableA's John to all of TableB's John, and all of TableA's Mary to all of TableB's Mary.

I should get the output

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)

I'm new to mySQL, and the above seems so complicated to me that I'm not even sure where to start.

I would really appreciate any help on this.

Upvotes: 2

Views: 142

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34581

If I understood you correctly, you need to issue two queries: one for finding records from TableA not existing in TableB, and second one for the opposite situation. Note that in one case it's LEFT JOIN and in the second case it's 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

Upvotes: 2

Related Questions