0

Question similar to this:

select from two tables where linked column can be null

column1tab1 column2tab1 order_number product amount
 xx            yy            123      p1      2
 xx            yy            456      p3      4
 xx            yy            NULL    NULL    NULL
 xx            yy            789      p2      1
 etc...

The poster's output was like above. However, when I add in WHERE product = 'p1', or alternatively WHERE product = NULL both return an empty set. Eventually, I want to have

SELECT            *
FROM              `t1`
  LEFT OUTER JOIN `t2`
  ON              (`t1`.`id` = `t2`.`id2`)
WHERE             `t2`.`product` = NULL
  AND             `t2`.`product` <> 'p1'

Which part am I doing wrong? The join or the where? Or something else?

Community
  • 1
  • 1
txchou
  • 647
  • 1
  • 6
  • 15
  • `product = NULL` would be `product IS NULL`, but beside that a null value automatically makes the second `product <> 'p1'` truthy. – Brad Christie Jun 25 '12 at 07:48

3 Answers3

2

Replace

`t2`.`product` = NULL

with

`t2`.`product` IS NULL

See here

Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
1

t2.product = NULL is always false. Use t2.product IS NULL instead.

b7kich
  • 4,253
  • 3
  • 28
  • 29
quzary
  • 285
  • 1
  • 4
0

If t2.product is null it is always different from the string 'p1'. I don't see the need for the and.

mihaisimi
  • 1,911
  • 13
  • 15