时间:2022-12-06 01:57
mysql排序的方法:使用MySQL的ORDER BY子句来设定你需要按照哪个字段以什么方式进行排序。
可以使用MySQL的ORDER BY子句来设定你需要按照哪个字段以什么方式进行排序。
ORDER BY子句语法:
SELECTfield1,field2,...fieldNFROMtable_name1,table_name2...ORDERBYfield1[ASC[DESC][默认ASC]],[field2...][ASC[DESC][默认ASC]]
示例:
读取runoob_tbl表中所有数据并按submission_date字段的升序排列。
mysql>useRUNOOB;Databasechanged
mysql>SELECT*fromrunoob_tblORDERBYsubmission_dateASC;
+-----------+---------------+---------------+-----------------+
|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|
+-----------+---------------+---------------+-----------------+
4rowsinset(0.01sec)
mysql>SELECT*fromrunoob_tblORDERBYsubmission_dateDESC;
+-----------+---------------+---------------+-----------------+
|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|
+-----------+---------------+---------------+-----------------+
4rowsinset(0.01sec)
还能够在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,"setnamesutf8");
$sql='SELECTrunoob_id,runoob_title,
runoob_author,submission_date
FROMrunoob_tbl
ORDERBYsubmission_dateASC';
mysqli_select_db($conn,'RUNOOB');
$retval=mysqli_query($conn,$sql);
if(!$retval)
{
die('无法读取数据:'.mysqli_error($conn));
}
echo'<h2>菜鸟教程MySQLORDERBY测试<h2>';
echo'<tableborder="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);
?>
输出结果: