python - 比较 SQLite 查询中两个可能为 NULL 的值

标签 python sqlite sql-null

我有一个 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/

相关文章:

python - 推荐快照数据的数据结构

android - 如何在 Android 中使用 SQLite 获得最佳性能?

java - SQL 查询有问题

sql - Postgresql 连接列并在列为 NULL 或为空字符串时跳过列

MySQL Workbench,NULL 的平均值返回 "0",我需要它返回 NULL

python - 如何访问Scrapy的项目类

python - PyQt:如何创建一个可滚动的窗口

python - 使 QGraphicsItem 只能在一个图形 View 中选择

python - Windows 任务计划程序,python 脚本,代码 2147942401

sql - 未明确说明时选择不包括空值