简体   繁体   中英

Select from two outer joined tables where a possible null column

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?

Replace

`t2`.`product` = NULL

with

`t2`.`product` IS NULL

See here

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM