完整的单条SQL:
select distinct column_name[,…] from table_name where condition group by column_name having condition order by column limit m,n;
查询语句的执行顺序
- 先执行 from
- 执行 where
- 执行 group by
- 执行 having
- 执行 select
- 执行 distinct
- 执行 order by
- 执行 limit
模糊查询
like 对应的通配符 % _
% 用于通配任意的n个字符
_用于通配任意的单个字符
要求查询名字以张开头的学生信息
SQL>select * from t_student where name like ‘张%’;
要求查询出名字中带z的用户信息
SQL>select * from user where name like ‘%z%’;
要求查询出名字中第二个字母是z的用户信息
SQL>select * from user where name like ‘_z%’;
如果% 和 _ 不需要当通配符处理,需要对其进行转译,使用
要求查询出名字中带_用户信息
SQL>select * from user where name like ‘%_%’;
排序 order by
对查询的结果进行排序
语法结构
select [distinct] column_name [,…] from table_name [where condition] [order by column_name asc|desc]
asc 表示升序排列,desc表示降序排列
例如:
select * from student order by age desc;
组函数
组函数能够出现在 select后面,having语句后面
常见的组函数:
max(column) : 统计column列的最大值 会忽略null值
min(column) : 统计column列的最小值 会忽略null值
sum(column): 统计column列的和值 会忽略null值 不纳入计算
avg(column): 统计column列的平均值 .如果column列有null值,是不纳入计算的。
在部分情况下,需要被平均。
count(column): 统计行数, 如果传递的是列名,会统计出该列所有的行数,不包括null值的
如果传递的是 * ,就直接统计所有行
2.7分组 group by
对你需要查询的数据进行分组
语法结构
select [distinct] column_name[,…] from table_name [where condition] [group by column] [order by column]
使用的group by 后如果想要查询其他列,只能使用分组过了列,也就是使用group by 的列。
例如:通过性别分组,查询男女各有多少人
select count(*) from student group by sex;
查询学生中最大的年龄
select max(age) from student ;
分组数据再过滤 having
having 用于对分组后的数据再过滤,不能单独使用。如果没有group by 是不能使用having的。
语法:
select [distinct] column_name[,…] from table_name [where condition] [group by column [having condition]] [order by column]
查询结果限定 limit
分页查询
select [distinct] column_name[,…] from table_name [where condition] [group by column] [order by column] [limit m,n]
m代表起始行,从0开始计算
n 代表页面大小,就是每页显示的数据量
假设page代表页码,pageSize代表每页显示的数据量
limit (page-1)*pageSize , pageSize;