MySQL语法
排序查询语法
select * from 表名 order by 列1 asc|desc [,列2 asd|desc,...]
语法说明
1、先按照列1进行排序,如果列1的值相同时,则按照列2排序,以此类推;
2、asc 从小到大排列,即升序;
3、desc 从大到校排序,即降序;
4、默认按照列值从小到大排列(即 asc 关键字)
例:
select * from student where isdelete=0 and gender = '男' order by id desc;
select * from student order by age desc, height desc;
分页查询语法
select * from 表名 limit start,count
语法说明
1、limit 是分页查询关键字;
2、start 表示开始行索引,默认是0;
3、count 表示查询条数;
例:
select * from student where gender='男' limit 0,3;
select * from student where gender='男' limit 3;
聚合函数
聚合函数又叫组函数,通常是对表中的数据进行统计和计算,一般结合分组(group by)来使用,用于统计和计算分组数据。聚合函数不对空值进行统计。
常用的聚合函数:
1、count(col): 表示求指定列的总行数
2、max(col): 表示求指定列的最大值
3、min(col): 表示求指定列的最小值
4、sum(col): 表示求指定列的和
5、avg(col): 表示求指定列的平均值
例:
select count(height) from student;
select max(id) from student;
select sum(height) from student where gender='男';
select sum(height) / count(*) from student where gender = '男';
select avg(height) from student where gender = '男';
select avg(ifnull(height,0)) from student where gender = '男';
分组查询
分组查询就是将查询结果按照指定字段进行分组,字段中数据相等的分一组。
分组查询基本的语法格式如下:
GROUP BY 列名 [HAVING 条件表达式][WITH ROLLUP]
说明:
*列名:是指按照指定字段的值进行分组;
*HAVING 条件表达式:用来过滤分组后的数据;
*WITH ROLLUP:在所有记录的最后加上一条记录,显示select查询时聚合函数的统计和计算结果
group by的使用
group by可用于单个字段分组,也可用于多个字段分组
例:
select gender from student group by gender;
如果指定了分组字段,那么查询的时候只能使用指定分组的字段
例:
select gender,name from student group by gender,name;
group by + group_concat()的使用
group_concat(字段名):统计每个分组指定字段的信息集合,每个信息之间使用都好进行分割
例:
select gender, group_concat(name) from student group by gender;
select gender,group_concat(age),count(*),avg(height) from student group by gender having count(*)>8;
连接查询
连接查询可以实现多个表的查询,当查询的字段数据来自不同的表就可以使用连接查询来完成。
连接查询可以分为:
1、内连接查询
2、左连接查询
3、右连接查询
4、自连接查询
内连接
查询两个表中符合条件的共有记录
内连接查询语法格式:
select 字段 from 表1 inner join 表2 on 表1.字段1 = 表2.字段2;
说明:
* inner join 就是内连接查询关键字
* on 就是连接查询条件
例:
select * from student as s inner join classes as c on s.cls_id = c.id;
select * from student inner join classes on student.class_id = classes.id;
左连接
以左表为主根据条件查询又表数据,如果根据条件查询右表数据不存在,使用null值填充
左连接查询语法格式:
select 字段 from 表1 left join 表2 on 表1.字段1 = 表2.字段2;
例:
select * from student as s left join classes as c on s.class_id = c.id;
右连接
以右表为主根据条件查询又表数据,如果根据条件查询左表数据不存在,使用null值填充
右连接查询语法格式:
select 字段 from 表1 right join 表2 on 表1.字段1 = 表2.字段2;
select * from student as s right join classes as c on s.class_id = c.id;
自连接查询
左表和右表时同一个表,根据连接查询条件查询两个表中的数据。
例:
select c.id, c.title, c.pid, p.title from areas c inner join areas p on c.pid = p.id;
子查询
在一个 select 语句中,嵌入了另外一个 select 语句,那么被嵌入的 select 语句称之为子查询语句,外部那个 select 语句则称为主查询。
主查寻和子查询的关系:
1、子查询是嵌入到主查询中的;
2、子查询是辅助主查询的,要么充当条件,要么充当数据源;
3、子查询是可以独立存在的语句,是一条完整的 select 语句。
例:
select * from student where age> (select avg(age) from student);
select * from classes as c inner join (select class_id,group_concat(name) from student group by class_id) as s on c.id = s.class_id;
select max(height) from student where age = (select max(age) from student);