I have a table (T1) and a table with attributes (T2). I’m looking to find records that have the same attributes as a record with provided id.
Here’s the example. Given 1 I want to find 2 (ensuring that attributes match as well).
T1
ID | A | B
----------
1 | k | l
2 | k | l
T2
IDFK | C | D
-------------
1 | w | x
1 | y | z
2 | w | x
2 | y | z
Here’s the SQL I have so far:
SELECT * FROM T1
JOIN T1 AS T1COPY ON T1.A = T1COPY.A, T1.B = T1COPY.B
JOIN T2 ON T1.ID = T2.IDFK
JOIN T2 AS T2COPY ON T1COPY.ID = T2COPY.IDFK
AND T2.C = T2COPY.C
AND T2.D = T2COPY.D
WHERE T1.ID = 1
but it’s not working right as it’s matching 2 even if attributes are different.
Here’s the answer for MySQL: http://www.sqlfiddle.com/#!2/ec4fa/2
Output for filter ID == 1:
From these inputs:
Explanation here: Find duplicates across multiple tables
MySQL query look a little bit convoluted as it doesn’t support FULL JOIN and it doesn’t have CTEs too. We simulate
FULL JOINby unioning the result ofLEFT JOINandRIGHT JOIN