Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

sql - MYSQL syntax not evaluating not equal to in presence of NULL

I am having trouble with a mysql query. I want to exclude values of 2. So I thought I would do following:

table products

id | name     | backorder
-------------------
1  | product1 | NULL
2  | product2 | NULL
3  | product3 | 2

SELECT name from `products` p
WHERE backorder <> '2'

However, This is not giving the desired result of product1, product 2 It is giving an empty results table.

On the other hand if I use

SELECT name from `products` p
WHERE backorder = '2'

Then it produces: product3. But I want to get those records where it is not equal to 2.

Something is not working with the <> '2'. Could it be that the NULL values are throwing it off? Can anyone suggest a fix.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use IS NULL or IS NOT NULL to compare NULL values because they are simply unknown.

SELECT name 
from   products p
WHERE  backorder IS NULL OR backorder <> 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...