`

sql 基础 2

    博客分类:
  • sql
阅读更多
请关注新浪微博 账号:大数据进行时(http://weibo.com/u/3272022684

1、order by
select name,sal,comm
from emp
order by 3; -- comm

2、空值排序、或者空值排在前面或后面
使用 case 来标记
select ename,sal,common
from(
select ename,sal,common,
case when common is null then 0
     else 1
end as is_null
from emp
) x
order by is_null,comm;

-------------------------------------------
1、记录集的叠加
UNION ALL
把多个表的行组合到一起;这些表不必具有相同的关键字,但是,他们对应列的数据类型应相同。
select ename as ename_and_dname , deptno
from emp
where deptno = 10
union all
select '----------' , null
union all
select dname , deptno
from dept

所有SELECT列表中的项的数目和类型必须要匹配。
UNION ALL 包括了重复的数据;如果要把重复的去掉,用UNION

通常:查询中使用UNION ALL,不使用UNION

2、从一个表中查找另一个表中没有的值(差集)
ORACLE支持差集操作:MINUS
select deptno from dept
minus
select deptno from emp;

如果不支持差集操作,使用如下SQL
select deptno from dept
where 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 e
where d.deptno = e.deptno(+)
and e.deptno is null;

4、查询中增加连接而不影响其他连接
查询员工的姓名、部门名、奖励日期(来自于奖励表)
如果使用where 语句,两个等值连接条件,只能获取有奖励的员工信息。
如下:
select e.name,d.loc,eb.received
from emp e, dept d, emp_bonus eb
where e.deptno = d.deptno
and e.empno = eb.empno;

解决此类问题,
(1)使用标量子查询:
select e.name, d.loc ,
        (select eb.received from emp_bonus eb where eb.empno = e.empno) as received
from emp e,dept d
where e.deptno = d.deptno;

(2)使用左外连接
select e.name,d.loc,eb.received
from emp e join dept d
on (e.deptno = d.deptno)
left out join emp_bonus eb
on(e.empno = eb.empno);

oracle:
select e.name ,d.loc,eb.received
from emp e, dept d ,emp_bonus eb
where e.deptno = d.deptno
and 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 子句中表的数量。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics