2

I need to get all records from table1 minus all (matching) records in table2. Green zone in the image.

The greenzone

The matching has to be done by pairs (values from 2 columns) Here is the query that I'm doing:

SELECT col1, col2 FROM table1 WHERE (col1, col2) NOT IN (SELECT col1, col2 FROM table2)

tabel1 has 317789 records and table2 has 289639 records. I got index(col1), index(col2) and index(col1, col2) on both tables.

Query is runnig for over than 30min now... Help!! :)

2
  • IN/NOT IN with multiple values can't use indexes in MySQL. You should avoid it. Commented Apr 13, 2018 at 14:53
  • See case four of A Visual Explanation of SQL Joins = second Left outer join, and adjust for using pairs. Commented Apr 16, 2021 at 10:13

2 Answers 2

4

I'd go with a null left join:

select col1, col2 from table1
left join table2 on table1.col1=table2.col1 and table1.col2 = table2.col2
where table2.<pk field> is null;

This will then show you the records from table1 that have no match in table2.

Note that pk field means whatever the primary key field in table2 is.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, running it now.
Query still taking more than 35min... Is this normal for the volume of records that i have?? A simple Left/Right/Inner JOIN takes less than a minute over the same tables...
It varies is all I can say. You could try something like: select * from table1 left join table2 on table2.key = (select key from table2 where table2.col1 = table1.col1 and table2.col2 = table1.col2) where table2.key is null;
1
SELECT table1.col1, table1.col2 
FROM table1 LEFT JOIN table2 
ON table2.col1 = table1.col1 AND table2.col2 = table1.col2

look at this "cheatsheet" of joins

enter image description here

4 Comments

This is good but not solve Drews problem. Should be 'where table2.pk is null'
You forgot the "is null" clause. But thanks for the cheat sheet ;)
The second one down on the left is the example you want. Also, iirc mysql does not support full outer joins, but there are ways to kludge one.
you are right. I would not edit my answer and agree with first answer :)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.