W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
我們知道從MySQL表中使用SQL SELECT 語(yǔ)句來(lái)讀取數(shù)據(jù)。
如果我們需要對(duì)讀取的數(shù)據(jù)進(jìn)行排序,我們就可以使用MySQL的 ORDER BY 子句來(lái)設(shè)定你想按哪個(gè)字段哪中方式來(lái)進(jìn)行排序,再返回搜索結(jié)果。
本章節(jié)使用的數(shù)據(jù)庫(kù)結(jié)構(gòu)及數(shù)據(jù)下載:MySQL.sql
以下是SQL SELECT 語(yǔ)句使用 ORDER BY 子句將查詢數(shù)據(jù)排序后再返回?cái)?shù)據(jù):
SELECT field1, field2,...fieldN FROM table_name1, table_name2...
ORDER BY field1, [field2...] [ASC [DESC]]
以下將在 SQL SELECT 語(yǔ)句中使用 ORDER BY 子句來(lái)讀取MySQL 數(shù)據(jù)表 w3cschool_tbl 中的數(shù)據(jù):
嘗試以下實(shí)例,結(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 子句的命令來(lái)獲取數(shù)據(jù)。 該函數(shù)用于執(zhí)行SQL命令,然后通過(guò) PHP 函數(shù) mysql_fetch_array() 來(lái)輸出所有查詢的數(shù)據(jù)。
嘗試以下實(shí)例,查詢后的數(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號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: