Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help regading not in and inner join

Tags:

sql

oracle

I have two tables. Table1 and Table2

Table1

id tid
1  100
2  200
3  300

Table2

tid name
100 A
200 B

I want to take out id of records from Table1 whichever's tid is not present in Table2.

My output should be like this.

Table1.id

3

For this i have written following queries but it is taking too much of time. Since both tables have more amount of records.

please help me how to write a query for this such a way that it will take less amount of time.

select id from Table1 where tid not in (select tid from Table2)
select a.id from Table1 a inner join Table2 b on a.tid<>b.tid

TIA.

like image 533
Navin Avatar asked Dec 06 '22 23:12

Navin


1 Answers

Use a left join, and then use the WHERE clause to filter only to rows where the join didn't work:

SELECT
     a.ID
from
     Table1 a
         left join
     Table2 b
         on
            a.tid = b.tid
where
    b.tid is null

Of course, this still might not work fast enough, in which case you need to check whether you have indexes on the tid columns in these two tables.

like image 184
Damien_The_Unbeliever Avatar answered Dec 26 '22 08:12

Damien_The_Unbeliever