SQL函数union,union all整理
阅读原文时间:2023年09月27日阅读:1

SQL集合函数--并集union,union all

本次整理从4个方面展示union函数,union all函数的风采:

1、集合函数使用规则

2、集合函数作用

3、数据准备及函数效果展示

首先1、集合函数使用规则

①   每个集合要求列数量相同,列顺序相同。

②   每个集合显示的列,要求数据类型一致或者可隐式转换成同一数据类型

③   最终集合列名称与第一个集合的列名称一致

2、集合函数作用

①     Union函数,合并多个结果集,且各结果集的重复行只保留一份,并按第一列升序显示

②     Union all函数,合并多个结果集,并不去除重复行,也不排序

3、数据准备及函数效果展示

①     创建表test_A,test_B

create table test_A ( id SMALLINT, name varchar(10) );
create table test_B ( id SMALLINT, name varchar(10) );

②     准备数据

---------------------------------------------------------
insert into test_A values(0,'张三');

insert into test_A values(1,'李四');

insert into test_A values(2,'王五');

insert into test_A values(3,'马六');

insert into test_B values(null,null);

insert into test_B values(1,'李四');

insert into test_B values(2,'孙七');

insert into test_B values(3,'周八');

③函数效果展示

select id,name from test_A
union
select id,name from test_B

select id,name from test_A
union all
select id id号,name 姓名 from test_B