I have a problem to compare two tables: A
id x
1 2
1 5
1 4
1 6
B
id x
1 2
1 5
1 4
1 6
I want to know if the data in table A and B are same with id=1.
This will list any rows with id=1
that are in a
but aren't in b
:
SELECT a.*
FROM a
LEFT JOIN b ON a.id = b.id AND a.x = b.x AND a.id = 1
WHERE b.x IS NULL;
In the left join, bx
will be null when there's an {a.id, ax} pair that doesn't have a corresponding {b.id, bx} pair.
To list any rows with id=1
that are in b
but not in a
, just turn the query around:
SELECT b.*
FROM b
LEFT JOIN a ON b.id = a.id AND b.x = z.x AND b.id = 1
WHERE z.x IS NULL;
Combine the two to find which rows are in a
but not b
and are in b
but not a
. If the query returns no rows then the values in both tables for id=1
are identical. If it does return rows, they're the ones that are different.
SELECT a.*, b.*
FROM a
LEFT JOIN b ON a.id = b.id AND a.x = b.x AND a.id = 1
WHERE b.x IS NULL
UNION SELECT a.*, b.*
FROM b
LEFT JOIN a ON b.id = a.id AND b.x = z.x AND b.id = 1
WHERE z.x IS NULL;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.