环境信息
数据库: mysql-5.7.20
操作系统: Ubuntu-16.04.3
查询
条件查询
# 使用 where 关键字
select * from 表名 where 条件
# 比较运算符
>,>=,<,<=,!=,=,<>
# 逻辑运算符
or,and,not
# 模糊查询 like
select * from 表名 where name like '%' # % 代表任意多个字符
select * from 表名 where name like 'T_' # _代表任意一个字符
# 范围查询
select * from 表名 where id in(1,2,3) # in 在一个非连续的范围内
select * from 表名 where id between 1 and 3 # between ... and ... 在一个连续的范围内, 全闭区间;
# 判空
select * from 表名 where name is null # 没有填写
select * from 表名 where name is not null # 判断非空
注意
运算的优先级由高到低的顺序为小括号, not, 比较运算符, 逻辑运算符
分组
# 关键字 group by
select age,count(*) from 表名 group by age # 通过年龄分组
# 关键字 having, 后面的条件和 where 一样
select age,count(*) from 表名 group by age having age>20 # 通过年龄分组, 然后对分组后的结果进行筛选
分页
# 关键字 limit
select * from 表名 limit start,count
# start 索引从 0 开始, 得到 count 条数据, 其按默认的 id 排序
排序
# 关键字 order by
# asc 按从小到大排序
# desc 按从大到小排序
# 规则为先按列 1 排序, 如果有相同的按列 2 排序, 否则按默认
select * from 表名 order by 列 1 asc|desc, 列 2 asc|desc;
常用聚合函数
说明: 聚合函数不能加载 where 的后面
count(*): 求列的总数; 当 count() 内的字段一定没有 null 值时, 统计的是列表的行数; 如果有 null 值, 统计的是该字段非 null 的个数;
select count(name) from 表名 where age > 20;
max(age): 求该列的最大值, 指定列名, 忽略 NULL 值; 对于非数字, 得到的是通过该列名排序后的最后一个
select max(age) from 表名 where age > 20;
min(age): 求该列的最小值, 指定列名, 忽略 NULL 值, 对于非数字, 得到的是通过该列名排序后的第一个
select min(age) from 表名;
sum(age): 该列之和, 指定列名, 忽略 NULL 值; 如果指定的列不是可运算的值, 结果为 0
select sum(age) from 表名;
avg(name): 求列的平均值, 对于非数字结果为 0;
select avg(age) from 表名;
连接查询
# 当查询结果的列来源于多张表时, 需要将多张表连接成一个大的数据集, 再选择合适的列返回
# 内连接 inner join
# 左连接 left join
# 右连接 right join
select * from 表 1 inner 或 left 或 right join 表 2 on 表 1. 列 = 表 2. 列
自关联
#表中的某一列,
关联了这个表中的另外一列#采用的依然是连接查询的方式;
子查询
# 标量子查询
# 列级子查询
# 行级字查询
# 表级字查询
格式: select * from 表名 where 条件 +(子查询)
关键字:
in: 在范围内;
any: 任何一个;
all: 等于所有;
来源: http://www.bubuko.com/infodetail-2482792.html