我有一个 SQLite 查询,如:
SELECT max(e), url, branch FROM (SELECT max(T1.entry) e, T1.url, T1.branch FROM repo_history T1
WHERE (SELECT active FROM repos T2 WHERE url = T1.url AND branch = T1.branch AND project = ?1)
GROUP BY T1.url, T1.branch
UNION
SELECT null, T3.url, T3.branch FROM repos T3 WHERE active AND project = ?1 )
GROUP BY url ORDER BY e
请注意,出现了两次
?1
范围。无论如何,在某些情况下,它可以为空(据我所知,python 中的 None
在 SQLite 中变为 NULL
)。这是一个问题,因为我不了解 null 处理,但基本上我没有得到任何返回。那么,我该如何处理
where "project" = ?1
当?1
是NULL吗?我想避免对它进行 2 个单独的查询。我环顾四周,但我只能找到有关 IS NULL
的信息。/IS NOT NULL
,这对我不起作用,因为我不是要检查列是否为空或不为空,而是要检查两个可为空的值是否匹配,是空值还是非空值。
最佳答案
在 SQLite 中,您可以使用 IS
运算符而不是 = 用于 NULL tolarant 比较。也适用于 ?
插入(不像 MikeT 的意思)。
python 示例:
>>> c.execute('SELECT * FROM mytable WHERE userid = ? AND recipe = ?', (3, None)).fetchall()
[]
>>> c.execute('SELECT * FROM mytable WHERE userid = ? AND recipe IS ?', (3, None)).fetchall()
[<Row object>, <Row object>]
>>> c.execute('SELECT * FROM mytable WHERE userid = ? AND recipe is ?', (3, 'TestRecipe')).fetchall()
[<Row object>]
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. Operators IS and IS NOT have the same precedence as =.
对于较旧的 MySQL/Mariadb 版本,至少 NULL tolarant 比较运算符是
<=>
在 PostgreSQL 中它的 IS NOT DISTINCT FROM
.PostgreSQL 变体在 SQL:2003 标准中定义。
为了临时兼容性,可以从 Python dict 中插入合适的运算符...
关于python - 比较 SQLite 查询中两个可能为 NULL 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207567/