Environmental information
Query criteria Query
# 使用where关键字select * from 表名 where 条件# 比较运算符>,>=,<,<=,!=,=,<># 逻辑运算符or,and,not# 模糊查询likeselect * 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 # 判断非空
The precedence of an operation is from high to low in the order of parentheses, not, comparison operators, logical operators
Group
# 关键字group byselect age,count(*) from 表名 group by age # 通过年龄分组# 关键字having,后面的条件和where一样select age,count(*) from 表名 group by age having age>20 # 通过年龄分组,然后对分组后的结果进行筛选
Page out
# 关键字limitselect * from 表名 limit start,count # start 索引从0开始,得到count条数据,其按默认的id排序
Sort
# 关键字order by# asc 按从小到大排序# desc 按从大到小排序# 规则为先按列1排序,如果有相同的按列2排序,否则按默认select * from 表名 order by 列1 asc|desc,列2 asc|desc;
Common aggregation functions
Description: The aggregation function could not be loaded after the 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值;如果指定的列不是可运算的值,结果为0select sum(age) from 表名;avg(name):求列的平均值,对于非数字结果为0;select avg(age) from 表名;
Connection Query
# 当查询结果的列来源于多张表时,需要将多张表连接成一个大的数据集,再选择合适的列返回# 内连接inner join# 左连接left join# 右连接right joinselect * from 表1 inner或left或right join 表2 on 表1.列=表2.列
Self-correlating
# 表中的某一列,关联了这个表中的另外一列# 采用的依然是连接查询的方式;
Sub-query
# 标量子查询# 列级子查询# 行级字查询# 表级字查询格式:select * from 表名 where 条件+(子查询)关键字:in:在范围内;any:任何一个;all:等于所有;
MySQL Foundation II