How to remove peer to peer records from two tables?

S.M_Emamian :

I have two table like this:

Table1

id      serial_id product_id
59867   152905  10005646
59871   152900  10005646
168832  147721  10005646
220695  147721  10005646

Table2

211399  152900
220248  147721

I want to keep these records:

serial_id
152905
147721 

my query:

SELECT REC.*
FROM Table1 REC
         LEFT JOIN Table2 REM ON REC.serial_id = REM.serial_id
WHERE
   REM.serial_id IS NULL;

but my query returns this result:

id      serial_id product_id
59867   152905  10005646

but at the first table I have two records of serial_id: 147721 I want to check these serials peer to peer and result must be:

id      serial_id product_id
59867   152905  10005646
220695  147721  10005646
Nick :

To get the result you want, you need to also look at the row number of each serial id in both tables, and add that to the JOIN. That way you can match each individual row in Table1 to one in Table2 and avoid removing both rows which have serial_id = 147721. Since you are using MariaDB 10.3 you can use CTEs and ROW_NUMBER():

WITH T1 AS (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY serial_id ORDER BY id) AS rn
  FROM Table1
),
T2 AS (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY serial_id ORDER BY id) AS rn
  FROM Table2
)
SELECT T1.id, T1.serial_id, T1.product_id
FROM T1
LEFT JOIN T2 ON T2.serial_id = T1.serial_id AND T2.rn = T1.rn
WHERE T2.id IS NULL

Output:

id      serial_id   product_id
220695  147721      10005646
59867   152905      10005646

Demo on dbfiddle

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276696&siteId=1