语法格式
SELECT field1, field2,…fieldN
FROM table_name1, table_name2…
[WHERE conditions]
ORDER BY field1 [ASC [DESC][默认 ASC]], [field2…] [ASC [DESC][默认 ASC]]
参数说明
在命令提示符中使用 ORDER BY 子句
SQL 排序
mysql> use RUNOON
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * from runoon_tbl ORDER BY submission_date ASC;
+-----------+---------------+---------------+-----------------+
| runoon_id | runoon_title | runoon_author | submission_date |
+-----------+---------------+---------------+-----------------+
| 4 | 学习 Python | RUNOON.COM | 2016-03-06 |
| 1 | 学习 PHP | 奔月教程 | 2021-10-16 |
| 2 | 学习 MySQL | 奔月教程 | 2021-10-16 |
+-----------+---------------+---------------+-----------------+
3 rows in set (0.00 sec)
mysql> SELECT * from runoon_tbl ORDER BY submission_date DESC;
+-----------+---------------+---------------+-----------------+
| runoon_id | runoon_title | runoon_author | submission_date |
+-----------+---------------+---------------+-----------------+
| 1 | 学习 PHP | 奔月教程 | 2021-10-16 |
| 2 | 学习 MySQL | 奔月教程 | 2021-10-16 |
| 4 | 学习 Python | RUNOON.COM | 2016-03-06 |
+-----------+---------------+---------------+-----------------+
3 rows in set (0.00 sec)
在 PHP 脚本中使用 ORDER BY 子句
MySQL ORDER BY 测试
<?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 runoon_id, runoon_title,
runoon_author, submission_date
FROM runoon_tbl
ORDER BY submission_date ASC';
mysqli_select_db( $conn, 'RUNOON' );
$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, MYSQLI_ASSOC))
{
echo "<tr><td> {$row['runoon_id']}</td> ".
"<td>{$row['runoon_title']} </td> ".
"<td>{$row['runoon_author']} </td> ".
"<td>{$row['submission_date']} </td> ".
"</tr>";
}
echo '</table>';
mysqli_close($conn);
?>
长按二维码,查阅更多教程
发表评论