create table student
(
id int primary key,
name nvarchar2(50) not null,
score number not null
);
insert into student values(1,'Aaron',78);
insert into student values(2,'Bill',76);
insert into student values(3,'Cindy',89);
insert into student values(4,'Damon',90);
insert into student values(5,'Ella',73);
insert into student values(6,'Frado',61);
insert into student values(7,'Gill',99);
insert into student values(8,'Hellen',56);
insert into student values(9,'Ivan',93);
insert into student values(10,'Jay',90);
commit;
·Union和Union All的区别。
select *
from student
where id < 4
union
select *
from student
where id > 2 and id < 6
结果将是
1 Aaron 78
2 Bill 76
3 Cindy 89
4 Damon 90
5 Ella 73
如果换成Union All连接两个结果集,则返回结果是:
1 Aaron 78
2 Bill 76
3 Cindy 89
3 Cindy 89
4 Damon 90
5 Ella 73
select score,id,name
from student
where id > 2 and id < 6
union
select score,id,name
from student
where id < 4
结果如下:
73 5 Ella
76 2 Bill
78 1 Aaron
89 3 Cindy
90 4 Damon
和我们预料的一致:将会按照字段的顺序进行排序。之前我们的查询是基于id,name,score的字段顺序,那么结果集将按照id优先进行排序;而现在新的字段顺序也改变了查询结果的排序。并且,是按照给定字段a,b,c...的顺序进行的order by。即结果是order by a,b,c...........的。我们看下一个查询:
select score,id,name
from student
where id > 2
union
select score,id,name
from student
where id < 4
结果如下:
56 8 Hellen
61 6 Frado
73 5 Ella
76 2 Bill
78 1 Aaron
89 3 Cindy
90 4 Damon
90 10 Jay
93 9 Ivan
99 7 Gill