目录
复杂查询
子查询(嵌套查询)
1. 查询工资高于平均工资的员工信息
select avg(sal) from emp; 2147
select * from emp where sal>(select avg(sal) from emp);
2. 查询工资最高的员工信息
select max(sal) from emp;
select * from emp where sal=(select max(sal) from emp);
3. 查询工资高于2号部门平均工资的员工信息
select * from emp where sal>(select avg(sal) from emp where deptno=2);
4. 查询和孙悟空相同工作的其它员工信息
select * from emp where job=(select job from emp where ename='孙悟空') and ename!='孙悟空';
关联关系(了解)
- 创建表时,表和表之间存在的业务关系.
- 有哪些关系:
1. 一对一:
有AB两张表,A表中一条数据对应B表中的一条数据,同时B表中一条数据对应A表中的一条数据称为一对一关系
2. 一对多:
有AB两张表,A表中一条数据对应B表中的多条数据,同时B表中一条数据对应A表中的一条数据称为一对多关系
3. 多对多:
有AB两张表,A表中一条数据对应B表中的多条数据,同时B表中一条数据对应A表中的多条数据称为多对多关系, 创建单独关系表保存多对多的关系
关联查询
- 笛卡尔积
关联查询时必须写两个表的关系,如果不写会得到两个表结果的乘积(称为笛卡尔积),笛卡尔积是一个错误的查询结果,切记工作中不要出现
关联查询的查询方式有三种:
等值连接
1. 查询每个员工的姓名和对应的部门名
select e.ename,d.dname
from emp e,dept d
where e.deptno=d.deptno;
2. 查询孙悟空和对应的部门名
select e.ename,d.dname
from emp e,dept d
where e.deptno=d.deptno and e.ename='孙悟空';
- 格式: select * from A,B where A.x=B.x and xxx=xxx;
内连接
- 内连接和等值连接查询的数据是一样的
- 格式: select * from A join B on A.x=B.x where xxx=xxx;
1. 查询每个员工的姓名和对应的部门名
select e.ename,d.dname
from emp e join dept d
on e.deptno=d.deptno;
2. 查询孙悟空和对应的部门名
select e.ename,d.dname
from emp e join dept d
on e.deptno=d.deptno
where e.ename='孙悟空';
- 等值连接和内连接查询到的是两张表的交集数据
外连接
- 外连接查询的是一张表的全部数据和另外一张表的交集数据
- 格式: select * from A left/right join B on A.x=B.x where xxx=xxx;
1. 查询所有部门名和对应的员工名
select d.dname,e.ename
from emp e right join dept d
on e.deptno = d.deptno;
insert into emp(empno,ename)values(50,'灭霸');
1. 查询所有员工和对应的部门名
select e.ename,d.dname
from emp e left join dept d
on e.deptno=d.deptno;
关联查询总结:
- 有三种关联查询的查询方式: 等值连接,内连接和外连接
- 如果需要查询两张表的交集数据使用等值连接或内连接(建议)
- 如果查询一张表的全部数据和另外一张表的交集数据则使用外连接.
DEBCP 数据库连接池
- DataBaseConnectionPool 数据库连接池
为什么使用DBCP
如果没有数据库连接池 一万次请求web服务器需要和数据库服务器建立一万次连接,频繁的开关连接非常浪费资源,使用连接池后可以将连接重用大大降低了连接的开关次数,从而提高执行效率