sql中and的优先级大于or(优先执行and)
in 等同于or
select 字段 from 表名 where xx in (条件);
in 后面括号里的值不是区间,是确切的值
like为模糊查询,支持%或下划线匹配
找出名字中带有o的(在模糊查询中,两个特殊的符号%和_,%代表任意多个字符,_代表任意一个字符)
select ename from emp where ename like '%o%';
找出名字中有下划线的
select name from t_user where name like '%\_%';
数据排序:
默认为升序(asc)降序为desc
多字段排序,越靠前起的主导作用越大
select … from … order by …, …;
分组函数/多行处理函数(对某一组数据进行操作,输出结果是一行):
count 计数
sum 求和
avg 平均值
max 最大值
min 最小值
分组函数自动忽略null值
空值处理:
ifnull(可能是null的数据,被当作…处理),是单行处理函数
select ..., ifnull(xxx, yyy) from ...;
如果xxx值是null,当作yyy处理
分组函数不能直接在where中使用
group by和 having:
group by:按照某个字段或某些字段进行分组
having:对分组之后的字段再次过滤
执行循序
select 5
...
from 1
...
where 2
...
group by 3
...
having 4
...
order by 6
...
找出工资高于平均工资的员工:
第一步:找出平均工资
select avg(sal) from emp;
第二步:找出高于平均工资的员工
select ename, sal from emp where sal > 2073.214;
select ename, sal from emp where sal > (select avg(sal) from emp);
子查询,select中嵌套select
where 优先于group by执行,having在group by后面执行,where的效率更高,所以能用where过滤的,尽量使用where
找出最高薪资大于2900的部门:
select max(sal), deptno from emp where sal > 2900 group by deptno;
无法使用where的情况:
找出每个部门的平均薪资,要求显示薪资大于2000的数据:
第一步:找出每个部门的平均薪资
select deptno, avg(sal) from emp group by deptno;
第二步:显示薪资大于2000的数据
select deptno, avg(sal) from emp group by deptno having avg(sal) > 2000;
dql语句总结:
select 5
...
from 1
...
where 2
...
group by 3
...
having 4
...
order by 6
...