I'm doing
我在做
Event.where(state: nil)
and get 1 result, but for Event.where('state = ?', nil)
get 0 results.
事件。其中(state: nil)得到1个结果,但对于事件。其中(state = ?', nil)得到0个结果。
What's the difference between these?
它们之间有什么区别?
2 个解决方案
#1
5
where(state: nil)
evaluates to WHERE events.state IS NULL
and other one evaluates to WHERE (state = NULL)
in SQL.
where(state: nil)计算事件。状态为NULL,另一个值计算到SQL中的WHERE (state = NULL)。
Now, A NULL
compared to anything returns NULL
, except if you use IS
operators. So, if you want to check if it is NULL
then use state IS NULL
, if not NULL
then state IS NOT NULL
.
现在,与任何返回NULL的值相比,空值都是NULL,除非使用的是操作符。如果你想检查它是否为空,那么use state为空,如果不是空,那么state为非空。
state = NULL
, returns NULL
, which, in WHERE
clause, is equivalent to FALSE
, that is why you got 0 records.
状态= NULL,返回NULL,在WHERE子句中,它等于FALSE,这就是为什么有0个记录。
events.state IS NULL
is the correct null comparisons so you got the output as you have in DB.
事件。状态为NULL是正确的空值比较所以就得到了DB中的输出。
#2
1
They generate different sql. When you have questions like this you can add a .to_sql to your relation and it will show you the sql that is generated and sent to the database.
他们产生不同的sql。当您有这样的问题时,您可以向您的关系添加.to_sql,它将显示生成并发送到数据库的sql。
Event.where(state: nil) produces this, which checks if x is a null like value
事件。这里(state: nil)生成这个,它检查x是否为空值
... WHERE events.state IS NULL
Event.where('state = ?', nil) produces this, which checks if X equals null which will never be true
事件。这里(state = ?, nil)产生了这个,它检查X是否等于null这永远都不会是真的
... WHERE (state = NULL)
#1
5
where(state: nil)
evaluates to WHERE events.state IS NULL
and other one evaluates to WHERE (state = NULL)
in SQL.
where(state: nil)计算事件。状态为NULL,另一个值计算到SQL中的WHERE (state = NULL)。
Now, A NULL
compared to anything returns NULL
, except if you use IS
operators. So, if you want to check if it is NULL
then use state IS NULL
, if not NULL
then state IS NOT NULL
.
现在,与任何返回NULL的值相比,空值都是NULL,除非使用的是操作符。如果你想检查它是否为空,那么use state为空,如果不是空,那么state为非空。
state = NULL
, returns NULL
, which, in WHERE
clause, is equivalent to FALSE
, that is why you got 0 records.
状态= NULL,返回NULL,在WHERE子句中,它等于FALSE,这就是为什么有0个记录。
events.state IS NULL
is the correct null comparisons so you got the output as you have in DB.
事件。状态为NULL是正确的空值比较所以就得到了DB中的输出。
#2
1
They generate different sql. When you have questions like this you can add a .to_sql to your relation and it will show you the sql that is generated and sent to the database.
他们产生不同的sql。当您有这样的问题时,您可以向您的关系添加.to_sql,它将显示生成并发送到数据库的sql。
Event.where(state: nil) produces this, which checks if x is a null like value
事件。这里(state: nil)生成这个,它检查x是否为空值
... WHERE events.state IS NULL
Event.where('state = ?', nil) produces this, which checks if X equals null which will never be true
事件。这里(state = ?, nil)产生了这个,它检查X是否等于null这永远都不会是真的
... WHERE (state = NULL)