下面的命令都是在Oracle11g下操作的。
SQLplus:Oracle的客户端
Oracle进入方式:
①cmd命令行
②SQLplus
③浏览器
1. 查询语句(select语句)【重要】
2. DML语句(操作数据)
3. DDL(数据定义语句)
Oracle11g DBA操作:
alter user scott account unlock; --scott解锁
desc + 表名字(); --显示表的内容
desc dual; --dual: 空表,计算数学表达式用
select sysdate from dual; --显示当前系统时间(显示一次)
含空值的表达式运算结果是空值
日期:
select ename, sal, hiredate from emp where hiredate > '20-2月-81'; --OK, 81年2月20日之后入职员工
select lower(ename) from emp; --名字变小写
select substr(ename, 2, 3) from emp; --截取字符串,从第二个字符开始共截取3个字符
select char(65) from dual; --把ASCII码转为字符 【有错误,还未找到】
select ascii('A') from dual; --把字符转为ASCII码(65)</span>
<span style="font-family: Arial, Helvetica, sans-serif;">select ascii('a') from dual; --97</span>
<span style="font-family: Arial, Helvetica, sans-serif;">四舍五入方法(记住有这些个函数就行,会查手册即可):</span>
select round(23.652) from dual; --四舍五入到个位,输出24(后面默认为0)
select round(23.652, 2) from dual; --四舍五入到百分位,输出23.65
select round(23.652, 1) from dual; --四舍五入到十分位,输出23.7
select round(23.652, -1)from dual; --四舍五入到十位,输出20
转换格式:
select to_char(sal, '$99,999.9999') from emp; --转换为 $1,100.0000形式
select to_char(sal, 'L99,999.9999') from emp; --转换为 ¥1,100.0000形式(本地货币)
select to_char(sal, 'L00000.0000') from emp; --转换为¥001100.0000形式</span>
select avg(sal) from emp; --结果:2073.21429
select to_char(avg<sal>, '99999999.99') from emp; --结果:2073.21
Notice: 数字转换,用得较少,知道即可。
日期转换【需要记住】(其他可随意组合):
to_char: 数字或日期转换为相关的字符串,且每种都有相关格式控制符
①to_date: 相关的特定格式字符串转为日期类型
②to_number: 特定格式的数字转为字符串类型
SQL> select to_char<hiredate, 'YYYY-MM-DD HH:MI:SS'> from emp;
select ename, hiredate from emp where hiredate > to_date('1981-2-20 12:34:56', 'YYYY-MM-DD HH24:MI:SS');
select sal from emp where sal > to_number('$1,250.00', '$9.999.99');
对运算中含null的处理:
select ename, sal*12 + nvl(comm, 0) from emp; --if null, comm = 0; else comm
组函数(5个)【都要牢记,重要】:
max() 最大值
min() 最小值
avg() 平均值
sum() 求和
count() 计数(非空记录个数)
eg:
select max(sal) from emp;
select count(*) from emp; --总共多少条记录
select count(ename) from emp;
select count(distinct deptno) from emp; --distinct 唯一的(去掉重复值)
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;">出现的错误:</span>
第 1 行出现错误:
ORA-00923: 未找到要求的 FROM 关键字
【注意】自己一直把 () 打成了 <>,之前的这种错误皆是由此造成。
select deptno, avg(sal) from emp group by deptno;
【小难点,好好理解一下】规则:select语句中,出现在列表中的字段,若没出现在组函数(5个)里,必须出现在group by中。
having: --对分组进行限制
select avg(sal), deptno from emp group by deptno having avg(sal) > 2000;
注意语句的执行顺序:
select * from emp
where
group by
having
order by
子查询(很灵活):
SQL> select ename, sal from emp where sal = (select max(sal) from emp); --谁的工资最高
SQL> select ename, sal from emp where sal > (select avg(sal) from emp); --高于平均工资的员工名字与工资