整合
SQL:数据查询核心
单表查询
数据源只有一个
select查询的字段列表 别名
from 数据源
where 条件
group by 分组字段
having 分组条件
多表查询
数据源多余一个
连接查询(1自然连接2内连接inner join3外连接outer join(左连接left join、右连接right join、全连接full join---笛卡尔积))
自连接(员工、领导)
主子查询
原理与概念
选择:从源表(关系)中选择符合条件的行---(元组 记录)
投影:从源表(关系)中选择符合条件的列---(属性 字段 列名)
连接:去掉重复属性的等值连接
回忆:
分组查询的条件?
查询中出现了,每个、各个、按年度、按季度之类的字眼或有此类意思的,有“谁”就group by“谁“
查询结果中有最大、最小、平均、计数、求和这5种聚合函数字段
整合
SQL:数据查询核心
单表查询
数据源只有一个
select查询的字段列表 别名
from 数据源
where 条件
group by 分组字段
having 分组条件
多表查询
数据源多余一个
连接查询(1自然连接2内连接inner join3外连接outer join(左连接left join、右连接right join、全连接full join---笛卡尔积))
自连接(员工、领导)
主子查询
原理与概念
选择:从源表(关系)中选择符合条件的行---(元组 记录)
投影:从源表(关系)中选择符合条件的列---(属性 字段 列名)
连接:去掉重复属性的等值连接
回忆:
分组查询的条件?
查询中出现了,每个、各个、按年度、按季度之类的字眼或有此类意思的,有“谁”就group by“谁“
查询结果中有最大、最小、平均、计数、求和这5种聚合函数字段
select查询的字段列表 别名
from 数据源
where 条件
group by 分组字段
having 分组条件
多表查询
数据源多一个
连接查询
查询工资高于公司平均工资的雇员信息
select *
from emp
where sal>(select avg(sal) from emp);
查询每个部门的编号和最低工资,要求最低工资大于等于部门为30的最低工资
select deptno,min(sal) 最低工资
from emp
group by deptno
having min(sal)>=(select min(sal) from emp where deptno=30);
查询部门名称、部门的员工数、部门的平均工资、部门的最低收入、雇员的姓名
--拆分
select deptno,count(empno),avg(sal),min(sal)
from emp
group by deptno;
select (select dename from dept where deptno=e.deptno) as dname,cont(empno),avg(sal),min(sal),(select ename from emp where sal=min(e.sal))
from emp e
group by deptno;
select d.dname,t.count,t.avg,e.ename
from(select deptno,count(empno) as count,avg(sal) as avg,min(sal)
as min from emp group by deptno) t,dept d,emp e
where d.deptno=t.deptno and e.sal=t.min;
查询平均工资最低的工作及平均工资
select min(t.avg)
from (select avg(sal) avg from emp group by job) t;
select job,avg(sal)
from emp
group by job
having avg(sal)=(select min(t.avg)
from (select avg(sal) avg from emp group by job) t);
3.2多行子查询
对于多行子查询,可以使用如下三种操作符
1.
in
例:查询所在部门编号大于等于20的雇员信息?
select * from emp where deptno>=20;
select * from emp where deptno in(select deptno from emp where deptno>=20);
查询工资与部门编号为20中的任意员工相同的雇员信息
select * from emp where sal in(select sal from emp where deptno=20);
1.
any some
>any:只要比子查询中最小的值大就可以
<any:只要比子查询中最大的值小就可以
=any:与任意一个相同,与此同时与in操作符的功能是相同的
select * from emp where sal>any(select sal from emp where deptno=20);
select * from emp where sal<any(select sal from emp where deptno=20);
select * from emp where sal=any(select sal from emp where deptno=20);
select * from emp where sal=some(select sal from emp where deptno=20);
1.
all
两种用法
>all:比子查询结果中最大的值要大
<all:比子查询结果中最小的值要小
select * from emp where sal>all(select sal from emp where deptno=20);
3.3多列子查询
多列子查询一般出现在from子句中,作为查询结果的结合
例:在所从事销售工作的雇员中找出工资大于1500的员工
select *
from(select * from emp where job='salesman') t
where t.sal>1500;
select * from emp where sal>1500 and job'salesman';
九、分页查询
1、limit关键字
用来限制查询返回的记录数
语法:
select 列名1 别名1,列名2 别名2,...
from 表名1 列名1 join 表名2 别名2 no 多表连接条件
where 分组前的条件
group by 分组字段
having 分组后的条件
order by 排序字段1 asc|desc,排序字段2 asc|desc
limit[参数1,]参数2
可以接收一个或两个数字
1.
参数1用来指定起始行的索引,索引默认从0开始,即第一行的索引的标记为0
1.
参数用来指定返回的记录