[英]How null is treated using union and union all in mysql?
based on below statement基于以下声明
select null
union
select null
the output of the above statement is:上述语句的输出是:
null
While this statement:虽然这个声明:
select null
union all
select null
Outputs:输出:
null
null
As null <> null
then how the value null is treated here and in which datatype it is considered作为null <> null
那么这里如何处理值 null 以及它被认为是哪种数据类型
In standard SQL, UNION
removes duplicate records, UNION ALL
does not.在标准 SQL 中, UNION
会删除重复的记录,而UNION ALL
不会。 Happlily your RDBMS is clever enough to figure out that NULL IS NULL
, and eliminates duplicate rows when UNION
is used.幸运的是,您的 RDBMS 足够聪明,可以弄清楚NULL IS NULL
,并在使用UNION
时消除重复行。
NB: null = null
is unknown
, however null <> null
is unknown
as well.注意: null = null
是unknown
的,但是null <> null
也是unknown
的。 The only way to check for nullity is to use something like IS NULL
.检查无效性的唯一方法是使用类似IS NULL
的东西。
SELECT case when null <> null then 1 else 0 end; --> yields : 0
SELECT case when null = null then 1 else 0 end; --> yields : 0
SELECT case when null IS null then 1 else 0 end; --> yields : 1
UNION
is a set operator and involves checking for "duplicate rows". UNION
是一个集合运算符,涉及检查“重复行”。 The specs define duplicate rows as "not being distinct".规范将重复行定义为“不明确”。 An excerpt from SQL-92 specs: SQL-92 规范的摘录:
Two values are said to be not distinct if either: both are the null value , or they compare equal according to Subclause 8.2, "<comparison predicate>".如果两个值是空值,或者它们根据第 8.2 节“<comparison predicate>”比较相等,则称两个值是不同的。 Otherwise they are distinct.否则它们是不同的。 Two rows (or partial rows) are distinct if at least one of their pairs of respective values is distinct.如果两行(或部分行)的相应值对中至少有一对不同,则它们是不同的。 Otherwise they are not distinct.否则它们是不明确的。 The result of evaluating whether or not two values or two rows are distinct is never unknown.评估两个值或两行是否不同的结果永远是未知的。
(emphasis mine). (强调我的)。 So, in this example:所以,在这个例子中:
select null
union all
select null
the two rows are considered duplicates of each other because the null values in first column are considered not distinct... ie same.这两行被认为是彼此重复的,因为第一列中的空值被认为是不同的......即相同。 And by definition UNION
returns only one row from a set of duplicate rows.根据定义, UNION
仅返回一组重复行中的一行。
I am considering that you know the difference between UNION (deduplicates results) and UNION ALL我认为您知道 UNION(去重结果)和 UNION ALL 之间的区别
select 'x' from dual where null is null \\results with x
In this case null is actually null.在这种情况下,null 实际上是 null。 Which means union returns correct result (deduplicated)这意味着 union 返回正确的结果(去重)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.