mysql之数据库操作进阶(三)

环境信息

  • 数据库: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:等于所有;
原文地址:https://www.cnblogs.com/cwp-bg/p/8390940.html