union
作用:把2次或多次查询结果合并起来(可以是一张表,也可以是两张或多张表)
要求两次查询的列数一致。

推荐查询的每一列,相对应的列类型也一样。

来自于多张表,
多次sql语句取出的列名可以不一致,此时以第一个sql的列名为准。


1,union all

2,有order by时,要把order by放到最后,对union后的新表起作用。

------------------------------------------

union把多张表合并起来,新表的内容就是两张表中所有的内容。
如果两张表对应列名的值相同,就会被覆盖,那么在合并后的新表中,只显示一次。
这时如果想要不被覆盖,就要用到union all
下面就是例子:

create table ta(id char(1),num int);

insert into ta 
values 
("a",5),
("b",10),
("c",15),
("d",20);


create table tb(id char(1),num int);

insert into tb 
values 
("b",10),
("c",10),
("d",15),
("e",20);


建好两张表后,两张表中id为“b”的值都是10,使用sql语句:
select * from ta union select * from tb;
查询出来的结果
id	num
a	5
b	10
c	15
d	20
c	10
d	15
e	20


从上面这张表可以看出"b"在新表中只出现了一次,想要不被覆盖都显示出来,可以使用union all:
select * from ta union all select * from tb;
查询出来的结果
id	num
a	5
b	10
c	15
d	20
b	10
c	10
d	15
e	20

进而算出两张表中相同id的总和:
select id,sum(num) from (select * from ta union all select * from tb) as tmp group by id;
如果不用union all,那么将会有数据丢失。

--------------------

有order by时,要把order by放到最后,对union后的新表起作用。
对新表中按num降序排列:
(select * from ta) union all (select * from tb) order by num desc;


有order by 和limit 配合使用时,
(select * from ta order by num desc limit 2) union all (select * from tb order by num desc limit 2);