Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get the rows not part of join

Tags:

sql

mysql

I am having below tables.

create table test(int id,int data1);
create table test1(int id,int data2);

insert into test values(1,1,);
insert into test1 values(2,2);
insert into test1 values(3,3);

insert into test1 values(1,1);

Now I want the rows of test, that don't participate in join. i.e I want rows (2,2) and (3,3). I want to be able to do this in mysql.

I don't want to use inner query because of performance.

Thank you

like image 913
Boolean Avatar asked Aug 05 '10 18:08

Boolean


People also ask

How do I exclude data from a SQL join?

Exclusion join is a product, merge, or hash join where only the rows that do not satisfy (are NOT IN) any condition specified in the request are joined. In other words, exclusion join finds rows in the first table that do not have a matching row in the second table. Exclusion join is an implicit form of the outer join.

How do you get not matching records from two tables using joins?

The JOIN or INNER JOIN does not return any non-matching rows at all. It returns only the rows that match in both of the tables you join. If you want to get any unmatched rows, you shouldn't use it. The LEFT JOIN and the RIGHT JOIN get you both matched and unmatched rows.

How can I get records not in another table?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


2 Answers

Using LEFT JOIN/IS NULL:

   SELECT t1.*
     FROM TEST1 t1
LEFT JOIN TEST t ON t.id = t1.id
                AND t.data1 = t1.data2
    WHERE t.id IS NULL

Assuming the columns being joined on, this is the fastest/most efficient method on MySQL. Otherwise, NOT IN/NOT EXISTS are better choices.

Using NOT EXISTS:

SELECT t1.*
  FROM TEST1 t1
 WHERE NOT EXISTS(SELECT NULL
                    FROM TEST t
                   WHERE t.id = t1.id
                     AND t.data1 = t1.data2)
like image 96
OMG Ponies Avatar answered Sep 23 '22 14:09

OMG Ponies


Without using sub queries (even the EXISTS variety which I love) you'll need to do a left join and grab the records that didn't join, like so:

select a.* from test1 a
left join test b on a.id = b.id and a.data2 = b.data1
where b.id IS NULL
like image 30
Fosco Avatar answered Sep 23 '22 14:09

Fosco