sql自学笔记(一)查询语句
语法结构:
select-from-where-group by-having-order by -limit
运行顺序:
from-where-group by-having-order by-limit=select
一. 基础查询
select 要查询的东西 from 表名
要查询的东西可以是常量值,可以是表达式,可以是字段,可以为函数
- 查询单个字段
select name from employees
- 查询多个字段
select name,email from employees
出现的顺序也按照所写字段中的顺序
- 查询表中所有字段
select * from employees
- 查询常量值
查询某个常量值时不需要来自哪个表
- 查询表达式
select 188*90
- 查询函数
select VERSION()
- 数据去重
select distinct department from empyees
对department字段中重复的行去重,只保留一个,若是多个字段的话,则去重所有字段重复的行
- +的作用
+号只有一个作用,就是运算符
select 100+90
select "123"+90#其中一方为字符型,试图将字符型转换为数值型,若转换成功,则继续做加法,若转换失败,则将字符型数值转换为0
select null+0,只要其中一方为null,则结果为null
- 利用contact函数实现拼接
如:查询员工名和姓连接成一个字段,并显示姓名
select contact('a','b','c') as 姓名
- ifnull 空值函数语句
ifnull (commission,0) as 奖金率
ifnull函数用于判断第一个表达式是否为null,若为null则返回第二个参数的值,如果不为null则返回第一个参数的值
二. 条件查询
select 要查询的东西 from 表名 where 筛选条件
- 条件表达式
> < >= <= != <>
(1)查询工资大于12000的员工
select * from employees where salary>12000
(2)查询部门标号不等于90号!=和<>的员工名和部门编号
select name,id from employees where id!=90
- 逻辑表达式
and or not
(1)查询编号不是在90到110之间,或者工资高于15000的员工
select * from employees where id<90 or id>110 or salary>15000
三. 模糊查询
like,between and ,in,is null,is not null
- like
一般和通配符搭配。%代表多个字符(包含0个字符)_任意单个字符
(1)查询员工名中第三个字符为e,第五个字符为a的员工和工资
select name,salary from employees where name like '__e_a%'
-
between and
包含临界值 -
in
判断某个字段的值是否属于in列表中的某项目,不支持通配符
(1)查询员工的工种编号是it,iit中的员工名和工种编号
select name,job from employees where id in ('it','iit')
- is null
(1)查询没有奖金的员工名
select name from employees where commision is null
(2)查询有奖金的员工名
select name from employees where commision is not null
三. 排序查询
select 要查询的东西 from 表 where 筛选 order by 排序的字段 asc|desc
若不写默认升序
(1)查询员工信息,要求先按工资排序,再按员工编号排序
select * from employees order by salary ASC,id desc
和limit联用
select 要查询的东西 from 表 limit [位置偏移量x,行数n]
从第x+1行开始返回n行
(1)返回排名前三行的数据
select name order by area desc limit3
(2)返回第100行到第200行
select * from nobel limit 99,21
四. 分组查询
select 分组函数,列(要求出现是group by 后面的字段)from 表 group by 分组列表
sum,max,min,avg,count
该分组函数都忽略null值。count(*)统计行数除外
sum和avg一般用于处理数值型,max,min,count可以处理任何数据类型
都可以搭配distinct使用,用于统计去重后的结果
- 添加分组前的筛选
(1)查询邮箱中包含a字符的每个部门的平均工资
select avg(salary),id from employees where email like '%a%' group by id
(2)查询有奖金的每个领导手下员工的最高工资
select max(salary),id from employees where commission is not null group by id
- 添加分组后的筛选条件having
(1)查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资
select max(salary),id from employees where commission is not null group by id having max(salary)>120000
- 按照表达式或函数分组
按员工姓名的长度分组,查询每一组员工个数,筛选员工个数>5有哪些
select count(),length(last_name)
from employees group by length(last_name) having count()>5
- 按多个字段分组
查询每个部门每个工种的员工的平均工资
select avg(salary),department_id,job_id from employees group by department_id,job_id order by avg(salary) desc
浙公网安备 33010602011771号