Oracle基础篇--03DML语言

1.数据准备:

--创建表格的
create table dept as select * from scott.dept;
create table emp as select * from scott.emp;
select * from dept;--部门表
select * from emp;--员工表

2.新增语句

【语法1】
INSERT INTO table_name (column1,column2,...)  VALUES ( value1,value2, ...);
【示例1】
insert into emp (empno,ename) values(1111,'luke');

【语法2】
INSERT INTO <table_name> <SELECT 语句>;
【示例2】

--创建table_test 
create table test_table as select * from emp where 1=2;

--插入工资大于2000的员工数据
insert into test_table select * from emp where sal>2000;

 

3.更新语句

【语法1】
UPDATE table_name SET column1=new value,column2=new value,... WHERE <条件>;
【示例1】
update emp set sal=3000 where ename='KING';
更新前:
更新后:

 4.删除语句

--根据条件删除表数据,有个习惯就是delete执行时要注意是否需要加where判断语句。
--【示例1】删除员工号等于1111的员工

delete from emp e where 1=1 and e.empno = '1111';

--清空表数据(表还在),不写日志,省资源,效率高,属于数据定义语言
--先创建要清空数据的表
create table myemp as select * from emp;
--清空表数据,不删除表结构
truncate table myemp;
 
5.查询语句(重点,因为工作中这个用的最多)

5.1 dual 伪表,是一个虚拟表,只是一个为了构成select语法

--查询序列下一位值
select [序列名].nextval from dual;
--查询当前的用户
select user from dual;
--查询当前系统时间
select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') from dual;

5.2 rowid 伪列,是一个数据库里面的唯一的物理地址,是插入一条记录时创建的地址。同一条记录,在不同的查询里的地址是相同的。

select e.*,e.rowid from emp e where 1=1 and e.ename = 'KING';

 

5.3 rownum ,是一个逻辑次序号,查询的时候生产,每次查询都会不同,并不是真实存在的编号。从1开始

select rownum,e.* from emp e where 1=1 and e.sal > 2000.00 and rownum <3;

使用rownum实现查询分页:

 

5.4 等值查询

select * from emp e,dept d where 1=1 and 

e.deptno = d.deptno;

5.5 左外/右外连接查询

select e.empno,e.deptno,d.deptno,d.dname from emp e left join dept d
on e.deptno = d.deptno
where 1=1 and e.sal > 2000;

5.6 分组查询

【示例1】

--查每个部门的平均工资
select d.deptno,d.dname,avg(e.sal) from emp e,dept d
where 1=1 and e.deptno = d.deptno
group by d.deptno,d.dname;

【示例2】

----查询平均工资大于2000的部门,并按照平均工资降序排序
select d.deptno,d.dname,avg(e.sal) from emp e,dept d
where 1=1 and e.deptno = d.deptno
having avg(e.sal) > 2000
group by d.deptno,d.dname;

【示例3】

--查询除了20部门以外,平均工资大于2000的部门
select d.deptno,d.dname,avg(e.sal) from emp e,dept d
where 1=1 and e.deptno = d.deptno
and e.deptno <> 20
having avg(e.sal) > 2000
group by d.deptno,d.dname;

5.7 模糊查询 like

【示例】

--查询部门名称第三个字符为‘C’的部门信息

select * from dept d
where 1=1 and d.dname like '__C%';

 

5.8 子查询

【示例】

--where后面的子查询;查询工资比10号部门员工中任意一个员工的工资低的员工信息
select * from emp e
where 1=1 and e.sal <(
select min(sal) from emp where 1=1 and deptno = 10
)

 以上只是一些总结,后续如果有新的内容,会继续补充进来。如果有发现sql有更优的查询,也欢迎和我交流。后续,我查找一下查用的查询联系题目作为巩固练习(附上答案)

posted on 2017-11-05 00:24  lukelin1989  阅读(136)  评论(0)    收藏  举报

导航