MySQL显然无法区分字符串

时间:2017-09-22 10:14:39

标签: mysql sql

我遇到了一个非常奇怪的案例:

select count(*) from shipments where user_id = 1 and pickup_id = 2返回 2

select count(*) from shipments where user_id = 1 and pickup_id = 2 and order_id = 'AAA'返回 1

select count(*) from shipments where user_id = 1 and pickup_id = 2 and order_id <> 'AAA'返回 0

到底是怎么回事?我正在使用MySQL 5.7.17

2 个答案:

答案 0 :(得分:2)

显然,order_id在一行中是NULL

使用:

而不是<>
select count(*)
from shipments
where user_id = 1 and pickup_id = 2 and
      (not order_id <=> 'AAA')

<=>NULL - 安全等式运算符(请参阅here)。 MySQL没有单NULL - 安全不等式,所以只需使用NOT或:

(order_id <> 'AAA' or order_id is null)

答案 1 :(得分:2)

可能order_id中存在空值。 &LT;&GT;不会解释这一点。

<>不是NULL容错的。但是'NOT IN'是。因此,而不是<>使用NOT IN

select count(*) from shipments where user_id = 1 and pickup_id = 2 and order_id NOT IN ('AAA')