将列与可能(或不)为空的值进行比较的最简单方法
Simplest way to compare column against a value that may (or not) be null
我有一个准备好的 SQLite 语句...
SELECT * FROM a WHERE col1 = $someValue
但是当someValue
是null
时查询returns没有行,所以我写了这个...
SELECT *
FROM a
WHERE (
col1 = $someValue OR
(
$someValue IS NULL AND
col1 IS NULL
)
)
无论 someValue
是否为 null
,此查询都能完美运行,但它非常冗长。 是否有更简单或更简洁的方法来实现同样的目标?
如果你要使用 postgres 有 is distinct from
我想他们有它是因为很多人和你有同感:
SELECT * FROM a WHERE col1 is not distinct from $someValue
使用 sqlite 应该可以这样写:
SELECT * FROM a WHERE col1 is $someValue OR col1 = $someValue
这可能是最短的了。
来自Operators, and Parse-Affecting Attributes:
The IS and IS NOT operators work like = and != except when one or both
of the operands are NULL. In this case, if both operands are NULL,
then the IS operator evaluates to 1 (true) and the IS NOT operator
evaluates to 0 (false). If one operand is NULL and the other is not,
then the IS operator evaluates to 0 (false) and the IS NOT operator is
1 (true). It is not possible for an IS or IS NOT expression to
evaluate to NULL.
您也可以使用运算符 IS
来比较非空值:
SELECT * FROM a WHERE col1 IS $someValue;
不如 forpas 的答案优雅,但另一个值得一提的选择:
SELECT * FROM a WHERE ifnull(col1, 'x') = ifnull($someValue, 'x')
传递给 ifnull
函数的第二个参数,在本例中为 x
,是数据库中不存在的值,col1
和 $someValue
是 varchar列。
我有一个准备好的 SQLite 语句...
SELECT * FROM a WHERE col1 = $someValue
但是当someValue
是null
时查询returns没有行,所以我写了这个...
SELECT *
FROM a
WHERE (
col1 = $someValue OR
(
$someValue IS NULL AND
col1 IS NULL
)
)
无论 someValue
是否为 null
,此查询都能完美运行,但它非常冗长。 是否有更简单或更简洁的方法来实现同样的目标?
如果你要使用 postgres 有 is distinct from
我想他们有它是因为很多人和你有同感:
SELECT * FROM a WHERE col1 is not distinct from $someValue
使用 sqlite 应该可以这样写:
SELECT * FROM a WHERE col1 is $someValue OR col1 = $someValue
这可能是最短的了。
来自Operators, and Parse-Affecting Attributes:
The IS and IS NOT operators work like = and != except when one or both of the operands are NULL. In this case, if both operands are NULL, then the IS operator evaluates to 1 (true) and the IS NOT operator evaluates to 0 (false). If one operand is NULL and the other is not, then the IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true). It is not possible for an IS or IS NOT expression to evaluate to NULL.
您也可以使用运算符 IS
来比较非空值:
SELECT * FROM a WHERE col1 IS $someValue;
不如 forpas 的答案优雅,但另一个值得一提的选择:
SELECT * FROM a WHERE ifnull(col1, 'x') = ifnull($someValue, 'x')
传递给 ifnull
函数的第二个参数,在本例中为 x
,是数据库中不存在的值,col1
和 $someValue
是 varchar列。