MySQL 排序
我們知道從MySQL 表中使用SQL SELECT 語句來讀取數據。
如果我們需要對讀取的數據進行排序,我們就可以使用MySQL的ORDER BY子句來設定你想按哪個字段哪中方式來進行排序,再返回搜索結果。
本章節使用的數據庫結構及數據下載: w3big.sql 。
語法
以下是SQL SELECT 語句使用ORDER BY 子句將查詢數據排序後再返回數據:
SELECT field1, field2,...fieldN table_name1, table_name2... ORDER BY field1, [field2...] [ASC [DESC]]
- 你可以使用任何字段來作為排序的條件,從而返回排序後的查詢結果。
- 你可以設定多個字段來排序。
- 你可以使用ASC 或DESC 關鍵字來設置查詢結果是按升序或降序排列。 默認情況下,它是按升序排列。
- 你可以添加WHERE...LIKE 子句來設置條件。
在命令提示符中使用ORDER BY 子句
以下將在SQL SELECT 語句中使用ORDER BY 子句來讀取MySQL 數據表w3big_tbl 中的數據:
實例
嘗試以下實例,結果將按升序排列
root@host# mysql -u root -p password; Enter password:******* mysql> use w3big; Database changed mysql> SELECT * from w3big_tbl ORDER BY w3big_author ASC; +-----------+---------------+---------------+-----------------+ | w3big_id | w3big_title | w3big_author | submission_date | +-----------+---------------+---------------+-----------------+ | 2 | Learn MySQL | Abdul S | 2007-05-24 | | 1 | Learn PHP | John Poul | 2007-05-24 | | 3 | JAVA Tutorial | Sanjay | 2007-05-06 | +-----------+---------------+---------------+-----------------+ 3 rows in set (0.00 sec) mysql> SELECT * from w3big_tbl ORDER BY w3big_author DESC; +-----------+---------------+---------------+-----------------+ | w3big_id | w3big_title | w3big_author | submission_date | +-----------+---------------+---------------+-----------------+ | 3 | JAVA Tutorial | Sanjay | 2007-05-06 | | 1 | Learn PHP | John Poul | 2007-05-24 | | 2 | Learn MySQL | Abdul S | 2007-05-24 | +-----------+---------------+---------------+-----------------+ 3 rows in set (0.00 sec) mysql>
讀取w3big_tbl 表中所有數據並按w3big_author 字段的升序排列。
在PHP腳本中使用ORDER BY 子句
你可以使用PHP函數的mysql_query()及相同的SQL SELECT 帶上ORDER BY 子句的命令來獲取數據。 該函數用於執行SQL命令,然後通過PHP 函數mysql_fetch_array() 來輸出所有查詢的數據。實例
嘗試以下實例,查詢後的數據按w3big_author 字段的降序排列後返回。
<?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'SELECT w3big_id, w3big_title, w3big_author, submission_date FROM w3big_tbl ORDER BY w3big_author DESC'; mysql_select_db('w3big'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Tutorial ID :{$row['w3big_id']} <br> ". "Title: {$row['w3big_title']} <br> ". "Author: {$row['w3big_author']} <br> ". "Submission Date : {$row['submission_date']} <br> ". "--------------------------------<br>"; } echo "Fetched data successfully\n"; mysql_close($conn); ?>