W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
我們知道從MySQL表中使用SQL SELECT 語句來讀取數(shù)據(jù)。
如果我們需要對讀取的數(shù)據(jù)進行排序,我們就可以使用MySQL的 ORDER BY 子句來設定你想按哪個字段哪中方式來進行排序,再返回搜索結(jié)果。
本章節(jié)使用的數(shù)據(jù)庫結(jié)構(gòu)及數(shù)據(jù)下載:MySQL.sql
以下是SQL SELECT 語句使用 ORDER BY 子句將查詢數(shù)據(jù)排序后再返回數(shù)據(jù):
SELECT field1, field2,...fieldN FROM table_name1, table_name2...
ORDER BY field1, [field2...] [ASC [DESC]]
以下將在 SQL SELECT 語句中使用 ORDER BY 子句來讀取MySQL 數(shù)據(jù)表 w3cschool_tbl 中的數(shù)據(jù):
嘗試以下實例,結(jié)果將按升序排列
root@host# mysql -u root -p password; Enter password: mysql> use W3CSCHOOL; Database changed mysql> SELECT * from w3cschool_tbl ORDER BY w3cschool_author ASC; +-------------+----------------+-----------------+-----------------+ | w3cschool_id | w3cschool_title | w3cschool_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 w3cschool_tbl ORDER BY w3cschool_author DESC; +-----------+------------------+-----------------+-----------------+ | w3cschool_id | w3cschool_title | w3cschool_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>
讀取 w3cschool_tbl 表中所有數(shù)據(jù)并按 w3cschool_author 字段的降序排列。
你可以使用PHP函數(shù)的mysql_query()及相同的SQL SELECT 帶上 ORDER BY 子句的命令來獲取數(shù)據(jù)。 該函數(shù)用于執(zhí)行SQL命令,然后通過 PHP 函數(shù) mysql_fetch_array() 來輸出所有查詢的數(shù)據(jù)。
嘗試以下實例,查詢后的數(shù)據(jù)按 w3cschool_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 w3cschool_id, w3cschool_title,
w3cschool_author, submission_date
FROM w3cschool_tbl
ORDER BY w3cschool_author DESC';
mysql_select_db('W3CSCHOOL');
$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['w3cschool_id']}
".
"Title: {$row['w3cschool_title']}
".
"Author: {$row['w3cschool_author']}
".
"Submission Date : {$row['submission_date']}
".
"--------------------------------
";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: