加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在PostgreSQL(可能还有其他引擎)中,为什么UNION语句认为NULL值相

发布时间:2020-12-13 16:02:58 所属栏目:百科 来源:网络整理
导读:我知道SQL标准允许列中的多个NULL值是UNIQUE约束的一部分. 我不明白为什么UNION构造(至少在PostgreSQL中)将NULL值视为相同.例如: $select * from tmp_a; a | b---+--- a | b a | |(3 rows)$select * from tmp_b; a | b---+--- a | c a | |(3 rows)$select a
我知道SQL标准允许列中的多个NULL值是UNIQUE约束的一部分.

我不明白为什么UNION构造(至少在PostgreSQL中)将NULL值视为相同.例如:

$select * from tmp_a;
 a | b
---+---
 a | b
 a |
   |
(3 rows)

$select * from tmp_b;
 a | b
---+---
 a | c
 a |
   |
(3 rows)

$select a,b from tmp_a union select a,b from tmp_b order by 1,2;
 a | b
---+---
 a | b
 a | c
 a |
   |
(4 rows)

解决方法

SQL-92标准中的一般规则如下:

13.1’声明游标'(记住ORDER BY是游标的一部分)
一般规则3b:

the following special treatment of
null values. Whether a sort key value
that is null is considered greater or
less than a non-null value is
implementation-defined,but all sort
key values that are null shall either
be considered greater than all
non-null values or be considered less
than all non-null values.

SQL-89对IMO说得更清楚一点:

Although x = y is unknown if both
x and y are NULL values,in the
context of GROUP BY,ORDER BY and
DISTINCT,a NULL value is
identical to or is a duplicate of
another NULL value.

我猜想PostgreSQL正在按照UNION的要求执行排序以删除重复项,并根据标准将NULL值分组在一起.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读