order by子句必须写在最后一个结果集里,并且其排序规则将改变操作后的排序结果;并且对于union、union all、intersect、minus都
union,对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;
union all,对两个结果集进行并集操作,包括重复行,不进行排序;
intersect,对两个结果集进行交集操作,不包括重复行,同时进行默认规则的排序;
minus,对两个结果集进行差操作,不包括重复行,同时进行默认规则的排序。
order by子句必须写在最后一个结果集里,并且其排序规则将改变操作后的排序结果;并且对于union、union all、intersect、minus都有效。
表头会用第一个连接块的字段。
1.unionunion用法中,两个select语句的字段类型匹配,而且字段个数要相同.
union连接的两个表是同一表,使用union会过滤重复行,显示的是一张表的数据。
下面sql查询语句中两个表完全一样,所以查询显示的是单张表的信息。
scott@bys1>select deptno,dname as aa,loc from dept union select deptno,dname,loc from dept;
deptno aa loc
---------- -------------- -------------
10 accounting new york
20 research dallas
30 sales chicago
40 operations boston
2.union allunion all,它的用法和union一样,只不过union含有distinct的功能,它会把两张表了重复的记录去掉,
而union all不会,所以从效率上,union all 会高一点,但在实际中用到的并不是很多.
效率上说,union all 要比union快很多,所以,如果可以确认合并的两个结果集中不包含重复的数据的话,那么就使用union all。
尽量使用union all,因为union需要进行排序,去除重复记录,效率低。
下面sql查询语句中两个表完全一样,所以查询显示了两次表内信息。
scott@bys1>select deptno,dname,loc as aa from dept union allselect deptno,dname,loc as bb from dept;
deptno dname aa
---------- -------------- -------------
10 accounting new york
20 research dallas
30 sales chicago
40 operations boston
10 accounting new york
20 research dallas
30 sales chicago
40 operations boston
3.intersect对两个结果集进行交集操作,不包括重复行,同时进行默认规则的排序;返回两个表共同含有的数据,取出交集作为最终的返回结果。
下面sql查询语句中两个表完全一样,,所以查询显示的是单张表的信息。
scott@bys1>select deptno,dname,loc as aa from dept intersect select deptno,dname,loc as bb from dept;
deptno dname aa
---------- -------------- -------------
10 accounting new york
20 research dallas
30 sales chicago
40 operations boston
4.minus对两个结果集进行差操作,不包括重复行,同时进行默认规则的排序。
第一个结果集减去第二个结果集中的内容,所剩余的内容作为最终的返回结果。
下面sql查询语句中两个表完全一样,所以查询显示无信息。
scott@bys1>select deptno,dname,loc as aa from dept minus select deptno,dname,loc as bb from dept;
no rows selected