mysql命令中的group by 和 order by li'mit使用与技巧

group by+聚合函数  公式:

max    最大值;

min    最小值;

avg    平均值;

sum    求和;

count    计算列数;

具体例子:

select  count(*) from  表名; #列出表中的列数

select  count(user) from  表名; #列出表中的user列的列数

#这里查询可以配合where使用

select  count(id) from   表名    where    name=root;#统计名字为root的id有多少

#不过我感觉这个count函数所用不多,不过后面的像max、min、sum用的比较多

下面用mysql自带的数据库中的user

select  user, count(host)  from  mysql.user;

select    user,count(user)  from    group  by   user;    #t统计user有多少用户并计算个数

#上述的像sum函数只要替换count函数就行了,但是需要有求和的需要才行。

order  by      对输出的数据进行排序

select user ,count(host) from  mysql.user group  by  user  order by host  ;     #统计user表中的host数并进行排序order by 排序默认升序,可以加人desc参数进行降序排列;

limit参数使用,应用场景一般和order  by 在一起使用作用是取数据的自定义行数;

select user ,count(host) from  mysql.user group  by  user  order by host   limit 5;    #去参数的前5行

猜你喜欢

转载自www.cnblogs.com/DB-MYSQL/p/11569965.html