sql 中 Union相关说明
结论
Union & Union all:
功能:将两个要连接的 SQL 语句拼接在一起,
要求:字段个数一样(强制),字段类型一致(非强制)int→double→string
输出:以第一个表的列名作为输出表的列名
区别:union会对拼接结果去重,union all 全部保留
>>> # check num of column
********select * from table1********
+---+------+------+
| id|score1|score2|
+---+------+------+
| a| 1| 2|
| a| 1| 2|
| b| 1| 2|
| b| 2| 3|
+---+------+------+
********select * from table2********
+---+------+------+------+
| id|score1|score2|score3|
+---+------+------+------+
| a| 1| 2| 3|
| b| 2| 3| 4|
+---+------+------+------+
>>> df3 = spark.sql(
"""
select *
from table1
union
select *
from table2
"""
)
>>> # Union can only be performed on tables with the same number of columns, but the first table has 3 columns and the second table has 4 columns
注:以int→double作为演示,string 就不演示了。
>>> # check type of column
>>> int→double→string
>>> df1.show()
+---+------+------+
| id|score1|score2|
+---+------+------+
| a| 1| 2|
| a| 1| 2|
| b| 1| 2|
| b| 2| 3|
+---+------+------+
>>> df2.show()
+---+------+------+
| id|score1|score2|
+---+------+------+
| a| 1.0| 2.0|
| b| 2.0| 3.0|
+---+------+------+
>>> df1.createOrReplaceTempView('table1')
>>> df2.createOrReplaceTempView('table2')
>>> df3 = spark.sql(
"""
select *
from table1
union
select *
from table2
"""
)
>>> df3.show()
+---+------+------+
| id|score1|score2|
+---+------+------+
| a| 1.0| 2.0|
| b| 2.0| 3.0|
| b| 1.0| 2.0|
+---+------+------+
>>> print(df1)
>>> DataFrame[id: string, score1: bigint, score2: bigint]
>>> print(df2)
>>> DataFrame[id: string, score1: double, score2: double]
>>> print(df3)
>>> DataFrame[id: string, score1: double, score2: double]
关于self-Union,奇怪的去重方式增加了
先看一段SQL
select *
from table1
union
select *
from table1
思考一下这段代码有没有用?
答案是有用的
实际上union操作并不会记录数据的来源,拼接完成后的数据表也是乱序的,table1 union table2在去重的时候:
并不是“选定table1,对比table2中的数据是否在table1中出现,如果出现,去除,如果未出现,保留,拼接为新表”
而是“汇总table1与table2表中的数据,对汇总后的数据进行去重”
所以下面两段SQL的作用是相同的(但是效率方面应该是不同的,这部分我没有进行验证)
select distinct *
from table1
--------------------------
select *
from table1
union
select *
from table1
为什么会注意到union操作的问题
select distinct *
from sample1
union
select distinct *
from sample2
union
select distinct *
from sample3
-- 以上是我的写法
----------------------------------------
-- 以下是别人的建议(提高SQL的运行效率)
select *
from sample1
union
select *
from sample2
union
select *
from sample3
题外话
spark底层对SQL的执行计划有优化,我们自己在写的时候,在union之前去重或者不去重是否会影响整体程序的性能,我还没有进行验证,努力学习,缩小差距。