表1 A B C 表2 A C Dselet * from 表1 union selet * from 表2 结果 A B C Dselet * from 表1 union all selet * from 表2 结果 A B C A C D
union 剔除一样的 union all 全部连接,不管一样不一样
union 删除重复行 union all 所有行(包括重复行)
union 有distinct 功能 Union all 不包含 所以如果要组合的表数据不重复,使用Union all 更快。
union 去重 union all 不去重直接关联
union 去重 union all 不去重直接关联
create table u1(id int) insert into u1 select 1 insert into u1 select 2 create table u2(id int) insert into u2 select 1 insert into u2 select 3 go select * from u1 union select * from u2 order by id desc select * from u1 union all select * from u2 order by id desc go drop table u1 drop table u2 ----------------------------id ----------- 3 2 1(所影响的行数为 3 行)id ----------- 3 2 1 1(所影响的行数为 4 行)
UNION 刪除重複行 UNION ALL 顯示所有
union不包含重复值,union all包含重复值
union 查询出来的结果会将不相同的数据显示出来,而完全相同的数据则只会显示其中一条记录.union all 所有行(包括重复行)
union all 不删除重复行 union 删除重复行 应用上述语句数据结构必须相同(包括字段和数据类型需相同)create table name1 (id int,name varchar(20),address varchar(50)) insert into name1(select '1','张三','北京') insert into name1(select '2','李四','深圳') insert into name1(select '3','王五','武汉') insert into name1(select '4','李明','上海') select id,name,address from name1
对的,union 去除重复数据了,union all 不去除重复数据,
Union对两个结果集进行合并操作,不包含重复行,同时进行默认规则的排序; Union all对两个结果集进行并集操作,包括重复行,不进行排序;
A
B
C
表2
A
C
Dselet * from 表1 union selet * from 表2
结果
A
B
C
Dselet * from 表1 union all selet * from 表2
结果
A
B
C
A
C
D
union all 全部连接,不管一样不一样
union all 所有行(包括重复行)
Union all 不包含
所以如果要组合的表数据不重复,使用Union all 更快。
union all 不去重直接关联
union all 不去重直接关联
insert into u1 select 1
insert into u1 select 2
create table u2(id int)
insert into u2 select 1
insert into u2 select 3
go
select * from u1 union select * from u2 order by id desc select * from u1 union all select * from u2 order by id desc
go
drop table u1
drop table u2
----------------------------id
-----------
3
2
1(所影响的行数为 3 行)id
-----------
3
2
1
1(所影响的行数为 4 行)
UNION ALL 顯示所有
union 删除重复行
应用上述语句数据结构必须相同(包括字段和数据类型需相同)create table name1 (id int,name varchar(20),address varchar(50))
insert into name1(select '1','张三','北京')
insert into name1(select '2','李四','深圳')
insert into name1(select '3','王五','武汉')
insert into name1(select '4','李明','上海')
select id,name,address from name1
Union all对两个结果集进行并集操作,包括重复行,不进行排序;