Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find non-existing data from another Table by JOIN?

I have two tables TABLE1 which looks like:

id      name     address
1       mm     123
2       nn     143

and TABLE2 w/c looks like:

name     age
mm      6
oo      9

I want to get the non existing names by comparing the TABLE1 with the TABLE2.

So basically, I have to get the 2nd row, w/c has a NN name that doesn't exist in the TABLE2, the output should look like this:

id      name     address
2      nn      143

I've tried this but it doesn't work:

SELECt  w.* FROM TABLE1 W INNER JOIN TABLE2 V
  ON W.NAME <> V.NAME

and it's still getting the existing records.

like image 522
Blair Yumi Avatar asked Sep 21 '11 04:09

Blair Yumi


People also ask

How do you get data from a table which is not present in another table?

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.

How do you join unrelated tables?

The most common way to join two unrelated tables is by using CROSS join, which produces a cartesian product of two tables. For example, if one table has 100 rows and another table has 200 rows then the result of the cross join will contain 100x200 or 20000 rows.

Can you inner join a table that doesn't have matching records?

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.


1 Answers

An INNER JOIN doesn't help here.

One way to solve this is by using a LEFT JOIN:

SELECT w.* 
FROM TABLE1 W 
LEFT JOIN TABLE2 V ON W.name = V.name
WHERE ISNULL(V.name);
like image 89
Bjoern Avatar answered Oct 25 '22 09:10

Bjoern