1、order byselect name,sal,commfrom emporder by 3; -- comm2、空值排序、或者空值排在前面或后面使用 case 来标记select ename,sal,commonfrom(select ename,sal,common,case when common is null then 0 else 1end as is_nullfrom emp) xorder by is_null,comm;-------------------------------------------1、记录集的叠加UNION ALL把多个表的行组合到一起;这些表不必具有相同的关键字,但是,他们对应列的数据类型应相同。select ename as ename_and_dname , deptnofrom empwhere deptno = 10union allselect '----------' , nullunion allselect dname , deptnofrom dept所有SELECT列表中的项的数目和类型必须要匹配。UNION ALL 包括了重复的数据;如果要把重复的去掉,用UNION通常:查询中使用UNION ALL,不使用UNION2、从一个表中查找另一个表中没有的值(差集)ORACLE支持差集操作:MINUSselect deptno from deptminusselect deptno from emp;如果不支持差集操作,使用如下SQLselect deptno from deptwhere deptno not in (select deptno from emp);3、在一个表中查找与其他表不匹配的记录如:查找没有职员的部门select d.* from dept d left out join emp e on(d.deptno = e.deptno) --左外连接,以左表为标准where e.deptno is null;oracle:select d.*from dept d ,emp ewhere d.deptno = e.deptno(+)and e.deptno is null;4、查询中增加连接而不影响其他连接查询员工的姓名、部门名、奖励日期(来自于奖励表)如果使用where 语句,两个等值连接条件,只能获取有奖励的员工信息。如下:select e.name,d.loc,eb.receivedfrom emp e, dept d, emp_bonus ebwhere e.deptno = d.deptnoand e.empno = eb.empno;解决此类问题,(1)使用标量子查询:select e.name, d.loc , (select eb.received from emp_bonus eb where eb.empno = e.empno) as receivedfrom emp e,dept dwhere e.deptno = d.deptno;(2)使用左外连接select e.name,d.loc,eb.receivedfrom emp e join dept don (e.deptno = d.deptno)left out join emp_bonus ebon(e.empno = eb.empno);oracle:select e.name ,d.loc,eb.receivedfrom emp e, dept d ,emp_bonus ebwhere e.deptno = d.deptnoand e.empno = eb.empno(+);5、检测两个表中是否有相同的数据也就是求交集;主要使用 UNION ALL 和 MINUS (oracle)比如有表 EMP 和 它的视图 V步骤如下:(1)找出EMP中存在而V中没有的行 (MINUS)(2)合并(UNION ALL)在V中存在而EMP中没有的行如果EMP和V是相等的,那么将没有数据返回;否则返回有差异的行。可以先查询基数是否相同:select count(*) from emp union select count(*) from v因为UNION会筛选重复的行,所以,如果两个表的基数一样,那么只会返回一行,否则返回两行。(也可以使用UNION ALL,看基数是否一样)6、消除笛卡尔积使用 n-1 规则;n 为from 子句中表的数量。
详细解决方案
sql 基础 二
热度:24 发布时间:2016-05-05 12:49:41.0
相关解决方案