码迷,mamicode.com
首页 > 数据库 > 详细

mysql order by

时间:2016-01-07 18:38:18      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:mysql

order by

排序:在结果集出来之后才有意义 必须在where ,group by ,having 之后

desc(降序)/asc(升序)


用字段排序  


用shop_price 降序排列

select goods_name,cat_id,shop_price from goods where cat_id=4 order by shop_price desc;


多个排序选择,先根据cat_id,然后shop_price

select cat_id,shop_price,goods_name from goods order by cat_id ,shop_price;


limit限制 limit [pos, 可选偏移量] 数量 


升序排列 取出前十名

select goods_id,goods_name from goods where cat_id=3 order by shop_price asc limit 10;


 

价格最高的前五名

mysql> select goods_name ,shop_price from goods order by shop_price desc limit 0,5;

等同

mysql> select goods_name ,shop_price from goods order by shop_price desc limit 5;

+----------------+------------+

| goods_name     | shop_price |

+----------------+------------+

| 多普达Touch HD      |    5999.00 | 

| 诺基亚N96           |    3700.00 | 

| 诺基亚N85           |    3010.00 | 

| testPhone      |    3000.00 | 

| 夏新T5             |    2878.00 | 

+----------------+------------+


价格最高的 从第三名开始的三名(或者说是第三名到第五名)

mysql> select goods_name ,shop_price from goods order by shop_price desc limit 2,3;

+------------+------------+

| goods_name | shop_price |

+------------+------------+

| 诺基亚N85       |    3010.00 | 

| testPhone  |    3000.00 | 

| 夏新T5         |    2878.00 | 

+------------+------------+



取出价格最高的商品

mysql> select goods_name ,shop_price from goods order by shop_price desc limit 1;

+----------------+------------+

| goods_name     | shop_price |

+----------------+------------+

| 多普达Touch HD      |    5999.00 | 

+----------------+------------+


技巧 :[判断where] [分组group_by] [过滤having] [排序order by] [筛选limit]



取出每个类型中 最新的产品

select cat_id, goods_id ,goods_name from(

(select cat_id,goods_id ,goods_name from goods order by cat_id desc,goods_id desc ) as tmp

)group by cat_id order by cat_id desc;


select cat_id,goods_id ,goods_name from goods where goods_id in (

select max(goods_id) from goods group by cat_id 

) order by cat_id desc;


查询出来的结果可以是

单列单行 可以用=   再次过滤

单列多行 可以用in  再次过滤

多列多行 可以用from 再次过滤


本文出自 “代码易” 博客,请务必保留此出处http://codeyi.blog.51cto.com/11082384/1732465

mysql order by

标签:mysql

原文地址:http://codeyi.blog.51cto.com/11082384/1732465

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!