(12B)order by 、limit

四、order by asc|desc
可以根据字段来排序,升序或者降序,默认是升序排列

//按照商品价格把栏目3的商品由高到低排序
select goods_id,goods_name,shop_price from goods where cata=3  order by shop_price asc ;

//将商品按照第一字段商品种类升序,第二字段商品价格降序,来排序
select goods_id,goods_name, cata, shop_price from goods order by cata ,shop_price desc;


//按商品的发布时间进行由早到晚排序(升序)
select * from goods order by goods_id;

五、limit在语句的最后,起到限制条目的作用

limit【offset,】N
offset:偏移 N:要的记录数
若不写offset,则从头开始取出
order by和limit 经常一起使用


//取价格的4-6个条目
select goods_id,goods_name,shop_price from goods order by shop_price desc limit 3,3;

//取最贵的商品
select goods_id,goods_name,shop_price from goods order by shop_price desc limit 0,1;

//取最新的商品
select goods_id,goods_name,shop_price from goods order by goods_id desc limit 0,1;

这5个子句是有顺序的:where,group by,having,order by,limit

//取每个栏目下的最贵的商品,以及价格

select cata,goods_id,goods_name,max(shop_price) from goods group by cata;(这是错的)
因为分组是以种类分类的,所以选出的列只能是种类和聚合函数,不能是其他内容,否则商品就是
分组后的第一个商品名和商品的id,而价格不一定相对应


select cata,goods_id,goods_name,max(shop_price) from goods group by cata order by shop_price desc;(错误)
因为先执行select cata,goods_id,goods_name,max(shop_price) from goods group by cata,得到了组代表,并且商品名
已经不对了,之后是对组代表进行了排序。


select cata,goods_id,goods_name,max(shop_price) from goods order by shop_price desc group by cata;(语法错误)


若每组的第一个数据都是最贵的商品,再从组中取最大的,就不会出现错误

//每组中第一个数据就是最大的:第一关键字:栏目(升序),第二关键字:商品价格(降序)
select goods_id,goods_name,cata,shop_price from goods order by cata,shop_price desc;


//因为查询得到的结果,也是表,所以可以直接查询
select * from (select goods_id,goods_name,cata,shop_price from goods order by cata,shop_price desc)as tmp group by cata;

理解模型
where表达式 :把表达式放在行中,看表达式是够为真
列:理解为变量,可以运算
取出结果:可以理解成一个临时表

posted @ 2017-08-12 19:49  测试开发分享站  阅读(195)  评论(0编辑  收藏  举报