Skip to content
Advertisement

Compare two tables via the three tables SQL

I plan to compare two tables via the three table. my query is as the following

Select count(*)
from tableA a
join tableB b
on a.A_ID =b.A_ID
full join tableC c
on c.B_ID=b.B_ID
where a.A_ID is null or c.B_ID is null 

if the count is zore, then the tableA and TableC match, otherwise, these two tables do not match

Table sample

It takes a long time to run the query. Do we have a way to compare tableA and tableC fast?

Question: How to compare tableA and tableC?

Advertisement

Answer

You don’t need a FULL JOIN here, you can just join the first two tables, then EXCEPT the third.

SELECT COUNT(*)
FROM (
    SELECT b.B_ID, a.A_Name
    FROM tableA a
    JOIN tableB b ON a.A_ID = b.A_ID
    EXCEPT
    SELECT c.B_ID, c.B_Name
    FROM tableC c
) t;

Note that EXCEPT implies DISTINCT so if you want the number of rows extra in table_A then you need to use WHERE NOT EXISTS

SELECT b.B_ID, a.A_Name
FROM tableA a
JOIN tableB b ON a.A_ID = b.A_ID
WHERE NOT EXISTS (SELECT 1
    FROM tableC c
    WHERE c.B_ID = b.B_ID AND c.B_Name = a.A_Name
);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement