Sql学习第一天——SQL UNION 和 UNION ALL 操作符认识

关于sql union 操作符

union 操作符用于合并两个或多个 select 语句的结果集。


注意

1.union 内部的 select 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 select 语句中的列的顺序必须相同。

2.union 结果集中的列名总是等于 union 中第一个 select 语句中的列名。

sql union 语法(结果集没有重复值):


复制代码 代码如下:

select s from table1

union

select s from table2

sql union all 语法(结果集有重复的值):


复制代码 代码如下:

select s from table1

union all

select s from table2

例子表:

 表一(employees_china):

    e_id e_name

    01    zhang, hua

    02    wang, wei

    03    carter, thomas

    04    yang, ming

 表二(employees_usa):

    e_id   e_name

    01    adams, john

    02    bush, george

    03    carter, thomas

    04    gates, bill

实例:

关于union: 


复制代码 代码如下:  

select e_name from employees_china

  union

  select e_name from employees_usa

结果如下(去除了重复数据):

e_name
zhang, hua
wang, wei
carter, thomas
yang, ming
adams, john
bush, george
gates, bill

关于union all:


复制代码 代码如下:

  select e_name from employees_china   

  union all

  select e_name from employees_usa

 结果如下(还保留了重复的数据):

e_name
zhang, hua
wang, wei
carter, thomas
yang, ming
adams, john
bush, george
carter, thomas
gates, bill
(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐