一、批量插入
1.在为创建表时插入旧表
SQL>
create table mytab as select *from emp;
2.在未建表时只批量插入一部分。
SQL> ed
已写入 file afiedt.buf
create table mytab2 as select empno,ename,job from emp
SQL> /
3.创建新表时,插入旧表格式以及个别字段,不插入内容时。
SQL>
create table mytab4 as select *from emp where 1=0;
4.在旧表批量插入别表数据
SQL>
insert into mytab4(empno,ename,sal) select empno,ename,sal from emp;
5.海量数据插入,使用begin end / 结束
SQL>
begin insert into emp values(1221,'lisi','manager',7788,'19-9月 -88',9998,1000,10); insert into emp values(1223,'wamhwu','manager',7788,'19-9月 -88',9998,1000,10); end; /
二、多表交叉查询
1.内连接 两种写法
内连接只会显示匹配成功的。
SQL>
1.
select * from emp e,dept d
where d.deptno = e.deptno ;
2.
select * fron emp e
inner join dept d
on d.deptno = e.deptno;
2.外连接
分为三大类
左外连接:以左表为基准,去匹配右表数据,如果匹配成功,则全部显示,匹配不成功,则显示部分
1.(Oracle独有连接)
select * from emp e,dept d
where d.deptno = e.deptno (+);
2.
select * fron emp e
left outer join dept d
on d.deptno = e.deptno;
右外连接:
与左连接相似
全外连接: 左外+右外-去重
自连接:
SQL>
select e.ename,d.ename from emp e,emp d where e.mgr=d.empno;
自连接优化:
层次连接:
condition:指一个或多个表达式和逻辑(布尔)运算符的组合,并返回TRUE、FALSE或UNKNOWN start with:指定层次查询的根数据行 connect by:指明父行和子行之间的关系:
select level,empno,ename,mgr from emp
connect by prior empno =mgr
start with mgr is null
order by level;
三、子查询
1.子查询可出现的位置where、select、having、from;不能写在group by 后面。
1)在where 后面;
SQL>
select *from emp where sal>(select sal from emp where ename='SCOTT');
2)在select后面,(但行列,常量列)
SQL>
select empno 第一列,ename 第二列,(select job from emp where empno = 7499) 第三列 from emp;
3).在having 后面;
SQL>
select deptno,min(sal) from emp group by deptno having min(sal)>(select min(sal) from emp where deptno=30);
4).在from后面;相当于修改了表结构
SQL>
select from (select empno,ename,sal12 from emp);
四、伪列
rownum:逻辑序列1 2 3 4 5
rowid:物理序列(18) 真实存放的位置
rownum:不同的Sql在执行时,rownum的值是不一致的。在相同Sql执行时,rownum值不变(在第一次查询的num之后保持不变。)
五、行转列及列转行
1.行转列case when eles end,使用函数来筛选;
MYsql建表
create table wyc_test( id int(32) not null auto_increment, name varchar(80) default null, date date default null, scount int(32), primary key (id) );
select a.date,
sum(case a.name when '小说' then a.scount else 0 end) 'sum小说', max(case a.name when '小说' then a.scount else 0 end) 'max小说', sum(case a.name when '微信' then a.scount else 0 end) '微信', max(case a.name when '小说' then a.scount else 0 end) 'max_微信' from wyc_test a group by date;
Oracle 练习写法
SELECT MAX(case WHEN DEPTNO = 10 THEN cnt ELSE 0 END) "10", MAX(case WHEN DEPTNO = 20 THEN cnt ELSE 0 END) "20", MAX(case WHEN DEPTNO = 30 THEN cnt ELSE 0 END) "30", SUM(cnt) 总人数 FROM (SELECT DEPTNO,COUNT(EMPNO) cnt FROM emp GROUP BY deptno)