数据库以后用的最多的应该就是查询了,那么数据库的高级查询就成了学习的重点.
我用数据库学习中常用的scott里面的emp表分析一下sql对数据库的高级查询
首先查询的基本语法:
select [distinct] * | 指定列名
from 表名
[where 条件] --分组前筛选
[group by 分组字段]
[having 条件] --分组后筛选
[order by 排序字段 asc|desc] -- 一定在最后
连接查询:从多张表中获取综合数据:
内连接: (inner join)
select emp.*,dept.*
from emp inner join dept
on dept.deptno=emp.deptno
外连接:left join right join
交叉连接:cross join
子查询:在sql语句中嵌套查询,必须使用()括起来
单行子查询:
select ename,deptno
from emp
where deptno=(select deptno from emp where ename=’SMITH’)
多行子查询:in,not in
select ename,job from emp
where job in(select job from emp where deptno=10)
分页查询:
取4-6条:
select * from (select rownum r,e,* from emp e)
where r >3 and r<=6
每页三条max=3
当前第二页 page=2
begin = (page-1)*max
end = begin+max;
查询时常用到的函数:
语法:
函数名() over (order by 排序字段 asc |desc)
分析函数:
row_number() --无论值是否相等,生成连续的行号
--12345678
dense_rank() --如果值相等,则排名相同,排名仍连续
--12234445678
rank() --如果值相等,则排名相同 ,排名不连续
--12335677710
case when then --该函数类似 java 的 swich
seslect ename,sal,case
when sal<=1000 then ‘☆’
when sal<=2000 then ‘☆☆’
when sal<=3000 then ‘☆☆☆’
when sal<=4000 then ‘☆☆☆☆’
when sal<=5000 then ‘☆☆☆☆☆’
单行函数:
日期函数:
sysdate---返回系统当前时间
select sysdate 当前时间 from dual
select sysdate-3 三天前 from dual
month_between(d1,d2) ---返回指定日期之间的月份间隔
add_months(d,num)--返回指定日期加上整数个月份之后的新日期
last_day(d)---返回指定日期当月的最后一天
字符函数:
length(str)----返回字符串的长度
--java下标从0开始; oracle下标从 1 开始
substr(str,index)
substr(str,index,length)
instr(str1,str2) ---返回str1中 str2出现的下标
&xxx 表示接收用户输入
select substr(‘&emil’,1,instr(‘&email’,’@’)-1) from dual;
转换函数:
to_char(sysdate,’yyyy”年”mm”月”yy”日”’)
to_char(sal,'$9,999.99')
--把目标转换为指定格式的字符串
to_date( , )
--把字符串转换为指定的日期格式
数学函数:
mod(n1,n2) ---n1%n2
ceil(num) ---进一取整
floor(num) ---舍去取整
round(num) /round(num,s)---四舍五入,s表示小数位数
trunc(num) /trunc(num,s) --阶段数字直接舍去,s表示小数位数
其他函数:
nvl(sal,0) --空值替换函数
decode() ---相当于case when then
---select ename,deptno,
decode(deptno,10,'技术部',20,'销售部',30,'管理层')
from emp;