[英]Mysql query won't work with a null column
I'm doing a relatively simple mysql query: 我正在做一个相对简单的mysql查询:
SELECT g.id FROM myTable g
WHERE g.timestamp > '0'
AND g.userId = '1'
AND g.foo != '34'
ORDER BY g.id DESC LIMIT 0, 10
This query returns 0 rows, however if I remove the last condition, ie change it to: 该查询返回0行,但是,如果我删除了最后一个条件,即将其更改为:
SELECT g.id FROM myTable g
WHERE g.timestamp > '0'
AND g.userId = '1'
ORDER BY g.id DESC LIMIT 0, 10
That returns 5-6 rows. 返回5-6行。 This is very strange to me, since in all of those rows, the int
column foo
is set to NULL 这对我来说很奇怪,因为在所有这些行中,将int
列foo
设置为NULL。
What am I doing wrong? 我究竟做错了什么?
Comparing something wilh NULL
will result in unknown
. 比较NULL
会导致unknown
。 That is why NULL
values have to be compared with the IS
operator. 这就是为什么必须将NULL
值与IS
运算符进行比较的原因。
Replace 更换
AND g.repostVia != '34'
with 与
AND (g.repostVia != '34' or g.repostVia is null)
or use the NULL-safe equality operator (thanks to eggyal): 或使用NULL安全相等运算符 (感谢eggyal):
AND NOT g.repostVia <=> '34'
The comparison g.repostVia != '34'
is FALSE
when g.repostVia
is NULL
because any comparison with NULL will allways be FALSE. 当g.repostVia
为NULL
时,比较g.repostVia != '34'
为FALSE
,因为任何与NULL的比较都将始终为FALSE。
You should make sure that you have covered this case (variable is NULL
) in any comparison with NULL-able column. 您应该确保在与NULL-able列的任何比较中都涵盖了这种情况(变量为NULL
)。
You can use IS NULL operator: 您可以使用IS NULL运算符:
SELECT g.id FROM myTable g
WHERE g.timestamp > '0'
AND g.userId = '1'
AND (g.repostVia, != '34' OR g.repostVia IS NULL)
ORDER BY g.id DESC LIMIT 0, 10
or COALESCE function: 或COALESCE函数:
SELECT g.id FROM myTable g
WHERE g.timestamp > '0'
AND g.userId = '1'
AND COALESCE(g.repostVia, -1) != '34'
ORDER BY g.id DESC LIMIT 0, 10
I myself prefer COALESCE, because it seems to me that it retains the original meaning of comparison better and as it allows more parameters it is also more flexible. 我自己更喜欢COALESCE,因为在我看来,它更好地保留了比较的原始含义,并且由于它允许更多参数,因此也更加灵活。
Maybe try <>
instead of !=
. 也许尝试<>
代替!=
。
0
values are tricky. 0
值很棘手。
Doing the comparison using IS NULL is definitely valid. 使用IS NULL进行比较绝对是有效的。 I want to offer that COALESCE() is often a bit more readable, if you have an invalid value that you can assign. 我想提供的是,如果您具有可以分配的无效值,那么COALESCE()通常更具可读性。 For instance, if g.foo is always positive, then the following would work: 例如,如果g.foo始终为正,则可以执行以下操作:
SELECT g.id FROM myTable g
WHERE g.timestamp > '0'
AND g.userId = '1'
AND coalesce(g.foo, -1) != '34'
ORDER BY g.id DESC
LIMIT 0, 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.