1

I have a query of the following type:

select * from tbl_1 where [cond] as aliasA LEFT JOIN tbl_2 as aliasB 
 ON (aliasA.id = aliasB.id) WHERE aliasB.id IS NULL

It appears that it's working except that it's ignoring the last WHERE aliasB.id IS NULL. So, it's just returning the results of:

select * from tbl_1 where cond as aliasA LEFT JOIN tbl_2 as aliasB 
 ON (aliasA.id = aliasB.id)

How would I change the above query to get the results of querying tbl_1 where [cond] displaying only the rows that are not in tbl_2?

Thanks in advance!

Plant More Trees
  • 65
  • 1
  • 1
  • 9

5 Answers5

6

aliasB.id = NULL will always be false. The correct way is aliasB.id IS NULL or the uglier MySQL-specific aliasB.id <=> NULL

Erik Ekman
  • 2,051
  • 12
  • 13
  • You're correct. Unfortunately, I meant to say IS NULL (which is how my code is written) but the results are as I said (not giving me what I want). I edited my post, correcting the IS NULL portion. – Plant More Trees Mar 14 '12 at 18:54
  • Then I think you should try and move the first condition to the `WHERE` clause after the join, like Marco writes. – Erik Ekman Mar 14 '12 at 18:58
6

Orignal Ans at : How do I decide when to use right joins/left joins or inner joins Or how to determine which table is on which side?

Best way i found is have look to below image clear out you doubt

Check the case 1 and 2 in image will give you your answer

and change you where condition to WHERE aliasB.id is NULL

alt text

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
3

You could try:

SELECT * FROM tbl_1 aliasA LEFT JOIN tbl_2 aliasB
ON aliasA.id = aliasB.id
WHERE condA 
  AND aliasB.id IS NULL
Marco
  • 56,740
  • 14
  • 129
  • 152
2

http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

You need to use "IS NULL" instead of "= NULL"

Griffin
  • 1,586
  • 13
  • 24
1

You need to use IS NULL to check for NULL values, not = NULL:

WHERE aliasB.id IS NULL
Ike Walker
  • 64,401
  • 14
  • 110
  • 109