最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

8)排序、分组|焦点热讯

来源:博客园

1、排序 order by:

order by:按照给定的字段或字段列表对结果集进行排序;asc是默认缺省值,升序排列;desc表示降序排序;


(相关资料图)

order by {col_name | expr | position} {[asc] | desc}    [,{col_name | expr | position} {[asc] | desc},...]

1)单列排序:

select * from choose order by score desc;

其中,null按最小值处理;

select stu_no,exam_score,regular_score, exam_score*0.8+regular_score*0.2 total_score    from exam    order by total_score desc;

可以看到按总分降序排列;上述也可以写成,将 结果集的第四列的total_score 写成 4:

select stu_no,exam_score,regular_score,exam_score*0.8+regular_score*0.2 total_score    from exam    order by 4 desc;

2)多列排序:

将 table_schema 升序排列,table_name 按降序排列;

select table_schema,table_name    from information_schema.tables    order by table_schema,table_name desc;

2、组函数:

1)组函数对null值会忽略掉;

select count(*),count(class_no) from student;
select count(score),avg(score) from choose;select max(choose_time),min(choose_time) from choose;

2)组函数参数使用distinct修饰;

select count(*), count(class_no),count(distinct class_no) from student;
select count(table_schema),count(distinct table_schema) from information_schema.tables;

3、分组:

group by子句将查询结果按照某个字段进行分组,字段值相同的作为一个分组,通常与聚合函数一起使用;

group by 字段列表[ having 条件表达式]

1)单列分组:

将每个学生的均分显示出来;

select student_no,avg(score) from choose    group by student_no;
select table_schema, count(*) cnt from information_schema.tables    group by table_schema;

2)多列分组:

将每个学生及其对应的名字分组;

select s.student_no,s.student_name,sum(score) 总分, avg(score) 平均分    from student s,choose c    where s.student_no = c.student_no    group by s.student_no,s.student_name;
select table_schema,table_type, count(*) cnt     from information_schema.tables    group by table_schema,table_type;

此处我们若是想进一步筛选计数值,可能会想到where子句来进行筛选;

我们可以看到:where子句中不能使用字段或表达式的别名,也不能使用组函数;

4)having 子句:

在group by筛选的基础上,若想进一步筛选,则需要用到having 子句;

having 条件表达式
select table_schema,table_type,count(*) cnt    from information_schema.tables    group by table_schema, table_type    having cnt >= 60;
select table_schema,table_type,count(*) cnt    from information_schema.tables    group by table_schema, table_type    having count(*) >= 60    order by cnt desc;

5)总结:

#语法顺序:select    from        where            group by                having                    order by#执行顺序:from    where        select            group by                having by                    order by

说明:

一旦有别名,那么所有字段都必须使用别名了,from 一定是最先执行的,没有from,就没有表,别名也是在这儿命名的;因此它是第一个执行的;

接着where 子句不能使用字段或表达式的别名,也不能使用组函数;因此它第二个执行;

select 字段是第三个执行,我们需要筛选的字段;

group by是筛选的基础上进一步分组;

having by 一定是在group by 的基础上有的;

最后是order by;

关键词: