SQL语句完整结构:
select from where group by having order by

今天分享的知识点:
(1)分组查询
select 中非组函数的列需要在group by 进行参与分组运算
where 后面不能使用组函数,having可以;如果使用非组函数过滤,优先使用where
增强分组查询group by rollup(a,b),先对a和b分组,再对a分组,再对null分组;

(2)自连接和外连接查询(全集,子集。全集表在哪边就是啥连接)
自连接
select e1.empno,e1.ename,e1.mgr,e2.ename from emp e1,emp e2 where e1.mgr=e2.empno(+);

sql99标准:
A a left join B b on a.col1=b.col2 左连接
A a right join B b on a.col1=b.col2 右连接
orcle:
A a , B b where a.col1(+)=b.col2 右连接
A a , B b where a.col1 =b.col2(+) 左连接

select d.deptno 部门编号,d.dname 部门名称,count(e.empno) 部门总人数 from emp e, dept d where e.deptno(+)=d.deptno
group by d.deptno,d.dname order by d.deptno;

(3) 等值连接
等值连接 where =
不等值连接 where between and,等


(4)子查询(select 语句的嵌套)
子查询放在哪里?select ,from ,where,having
子查询用什么关键字连接?单行子查询使用(=,<>,>,>=,<,<=,between and),多行子查询使用单行运算符和(in(),any(),all())
子查询和主查询执行顺序?一般首先执行子查询,相关子查询首先执行主查询;
子查询一般参与排序么?一般不参与排序,但是在分页查询中需要对子查询排序;
相关子查询需要注意什么?主查询的结果可以以参数传递给子查询使用
对多行子查询not in()不能使用null的理解

(5)层次查询(针对的是一张表,该表中存在tree的结构)
connect by prior empno=mgr start with mgr is null

(6)分页查询
一张表不经过任何操作默认带有rownum行号,经过排序操作之后,该行号也随着排序了,但不是从1-2-3排序的
为了重新按照1-2-3排序,需要将参与排列的表放入from中构成一张新的表;新表的顺序是按照1-2-3排序的
rownum 不能直接rownum>1,但是可以使用rownum<6
为了使用rownum>1,我们把rownum当成列来使用而不是行号;
select * from (select rownum rm,e1.* from (select rownum,e.* from emp e order by sal desc)
e1 where rownum<8 ) e2 where rm>2;
(7)集合操作
union 去重,union all不去重
集合参与运算(并集,交集,差集)需要每一个集合的列个数和类型要一样;
order by放在最后;
set timing on
(8)临时表
create global temporary xx on commit delete rows;

注意:

自然连接(显示的只能是* ,不能使用on 有一个连接条件)
select * from emp natural join dept;

交叉连接(产生了笛卡尔积)
select e.ename,d.dname from emp e cross join dept d;

内连接(在笛卡尔积上选择了满足on条件的记录行)
显式内连接:select * from emp e inner join dept d on e.deptno=d.deptno;
隐式内连接:select * from emp e , dept d where e.deptno=d.deptno;

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!