mysql排序的方法:使用MySQL的ORDER BY子句來設定你需要按照哪個字段以什么方式進行排序。
可以使用MySQL的ORDER BY子句來設定你需要按照哪個字段以什么方式進行排序。
ORDER BY子句語法:
SELECT field1, field2,...fieldN FROM table_name1, table_name2...ORDER BY field1 [ASC [DESC][默認 ASC]], [field2...] [ASC [DESC][默認 ASC]]
示例:
讀取runoob_tbl表中所有數據并按submission_date字段的升序排列。
mysql> use RUNOOB;Database changed
mysql> SELECT * from runoob_tbl ORDER BY submission_date ASC;
+-----------+---------------+---------------+-----------------+
| runoob_id | runoob_title | runoob_author | submission_date |
+-----------+---------------+---------------+-----------------+
| 3 | 學習 Java | RUNOOB.COM | 2015-05-01 |
| 4 | 學習 Python | RUNOOB.COM | 2016-03-06 |
| 1 | 學習 PHP | 菜鳥教程 | 2017-04-12 |
| 2 | 學習 MySQL | 菜鳥教程 | 2017-04-12 |
+-----------+---------------+---------------+-----------------+
4 rows in set (0.01 sec)
mysql> SELECT * from runoob_tbl ORDER BY submission_date DESC;
+-----------+---------------+---------------+-----------------+
| runoob_id | runoob_title | runoob_author | submission_date |
+-----------+---------------+---------------+-----------------+
| 1 | 學習 PHP | 菜鳥教程 | 2017-04-12 |
| 2 | 學習 MySQL | 菜鳥教程 | 2017-04-12 |
| 4 | 學習 Python | RUNOOB.COM | 2016-03-06 |
| 3 | 學習 Java | RUNOOB.COM | 2015-05-01 |
+-----------+---------------+---------------+-----------------+
4 rows in set (0.01 sec)
還能夠在PHP腳本中使用ORDER BY子句。
php示例如下:
<?php$dbhost = 'localhost'; // mysql服務器主機地址
$dbuser = 'root'; // mysql用戶名
$dbpass = '123456'; // mysql用戶名密碼
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('連接失敗: ' . mysqli_error($conn));
}
// 設置編碼,防止中文亂碼
mysqli_query($conn , "set names utf8");
$sql = 'SELECT runoob_id, runoob_title,
runoob_author, submission_date
FROM runoob_tbl
ORDER BY submission_date ASC';
mysqli_select_db( $conn, 'RUNOOB' );
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('無法讀取數據: ' . mysqli_error($conn));
}
echo '<h2>菜鳥教程 MySQL ORDER BY 測試<h2>';
echo '<table border="1"><tr><td>教程 ID</td><td>標題</td><td>作者</td><td>提交日期</td></tr>';
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC))
{
echo "<tr><td> {$row['runoob_id']}</td> ".
"<td>{$row['runoob_title']} </td> ".
"<td>{$row['runoob_author']} </td> ".
"<td>{$row['submission_date']} </td> ".
"</tr>";
}
echo '</table>';
mysqli_close($conn);
?>
輸出結果: