order by子句可用于按列升序或降序对select查询将结果集进行排序。
SELECT select_export [, select_export ...] FROM table_name ORDER BY column_name(s) ASC|DESC
SELECT 查询输出语句 FROM 数据表名 ORDER BY 列名 升序|降序
在test数据库里user表有以下数据:
+------+---------+----------+ | id | Name | password | +------+---------+----------+ | 1 | zhansan | 123 | | 2 | lisi | 345 | | 3 | liming | 456 | +------+---------+----------+
下面的例子选取 "user" 表中的存储的所有数据,并根据 "id" 列对结果进行降序:
<?php $link = @mysqli_connect('localhost', 'root', 'root', 'test','3306'); if (!$link) { die('连接失败!'.mysqli_connect_error()); }else{ $sql = "select * from user order by id desc"; $result = mysqli_query($link,$sql); echo "<table border='1'> <tr> <th>id</th> <th>name</th> <th>password</th> </tr>"; if (mysqli_num_rows($result) > 0) { // 输出数据 while($row = mysqli_fetch_array($result)) { //print_r($row);die(); echo "<tr>"; echo "<td>" . $row[0] . "</td>"; echo "<td>" . $row[1] . "</td>"; echo "<td>" . $row[2] . "</td>"; echo "</tr>"; } echo "</table>"; } else { echo "0 结果"; } //mysqli_free_result函数释放结果内存 mysqli_free_result($result); } ?>
可以根据多个列进行排序。当按照多个列进行排序时,只有第一列相同时才使用第二列:
SELECT select_export [, select_export ...] FROM table_name ORDER BY column_name1 ASC|DESC, column_name2 ASC|DESC