MySql 分组与统计函数

group分组与统计函数:

统计函数:

max()

count()

avg()

min()

sum()

在sql中重复要用的语句:用as名字新变量,以便调用

select goods_id,goods_name,(market_price-shop_price) as save from goods

having -- 对查询出来的结果集进行筛选

where 不能写在having后面

order by :(默认升序asc) 降序asc(排序很浪费资源)

select goods_id,goods_name,shop_price from goods order by  shop_price desc;

limit用法:(做分页类能用到)

限制取出条目(limit有两个参数 :偏移量 取出的条目)

select goods_id,goods_name,shop_price

-> from goods

-> order by shop_price desc

-> limit  0,3;

子句的查询陷阱:

5种语句有严格的顺序,where ,group by,having,order by,limit

不能颠倒顺序

例子: #语句有严格的顺序

mysql> select id,sum(num)

-> from

-> (select * from a union select * from b) as temp

-> group by id

-> having sum(num)>10

-> order by sum(num) desc

-> limit 0,1;

子查询:

where字查询:(内层的查询结果作为外层的比较条件)

静态的:select goods_id,goods_name from goods where goods_id=32;

动态的:select goods_id,goods_name from goods where goods_id=(select max(goods_id) from goods);

#取出每个栏目下最新的商品:

select goods_id,cat_id,goods_name from goods where goods_id in (select max(goods_id) from goods group by cat_id);

from子查询:

#每个栏目下最新的商品:

mysql> select goods_id,goods_name from (select * from goods where 1 order by cat_id desc) as tmp

-> group by cat_id;

exists子查询:

#查询栏目下是否有商品

mysql> select * from category

-> where exists(select * from goods where goods.cat_id=category.cat_id)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mysql的查询、子查询及连接查询 一、mysql查询的五种子句 where(条件查询)、having(筛选)、g...
    时芥蓝阅读 3,904评论 0 3
  • 一、mysql查询的五种子句 where(条件查询)、having(筛选)、group by(分组)、order ...
    化城阅读 5,574评论 0 9
  • 数据库基础知识 数据库客户端MySQL作为数据库服务器来运行,任何满足mysql通信规范的软件都可以作为客户端来连...
    littlexjing阅读 4,522评论 0 2
  • 我都不知道这二十多天我是怎么走过来的,我怎么坚持书写的,曾经有很多次,我都想放弃,我都懒得写。而且我准备写我...
    byseam阅读 1,774评论 3 0
  • 姑娘你这么漂亮 何必在海边独自忧伤 花开满树 碧海生潮 脚下沙子柔软的发痒 头顶一夜韶光 你抬头看海 我低头看你 ...
    面包树和安娜阅读 1,443评论 0 1