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 再次過濾