sql - 在PostgreSQL(可能还有其他引擎)中,为什么UNION语句将NULL值视为相同,而UNIQUE约束却不这样呢?

标签 sql null duplicates union dbnull

我了解SQL标准在作为UNIQUE约束的一部分的列中允许多个NULL值。

我不明白的是为什么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值组合在一起。

关于sql - 在PostgreSQL(可能还有其他引擎)中,为什么UNION语句将NULL值视为相同,而UNIQUE约束却不这样呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5725000/

相关文章:

c# - 我可以从 SELECT 语句中获得 SQL 注入(inject)攻击吗?

mysql - 每个唯一列值获取一条记录

java - 如果我在 Java 中使用 HashMap<String, ArrayList<String>>

objective-c - 在 nil 上调用 Block_copy() 和 Block_release() 是否安全?

sorting - 删除只有一个变量不同的观察结果

删除 r 中的相邻重复项

mysql - 查找员工平均工资高于 “Wipro” 处平均工资的公司

sql - Oracle SQL - 从具有重复节点的 XML 中提取 clob 值

null - PHP 回显 `null` 值

java - 使用 PrintWriter 时删除 ".dat"文件中的空值行