扫码一下
查看教程更方便
我们知道从 mysql 表中使用 sql select 语句来读取数据。
如果我们需要对读取的数据进行排序,我们就可以使用 mysql 的 order by 子句来设定你想按哪个字段哪种方式来进行排序,再返回搜索结果。
以下是 sql select 语句使用 order by 子句将查询数据排序后再返回数据:
select field1, field2,...fieldn from table_name1, table_name2...
order by field1 [asc [desc][默认 asc]], [field2...] [asc [desc][默认 asc]]
以下将在 sql select 语句中使用 order by 子句来读取mysql 数据表 jiyik_tbl 中的数据:
以下示例将按 submission_date 字段分别对select查询结果进行升序和降序排列。
mysql> select * from jiyik_tbl order by submission_date asc;
---------- ---------------- -------------- -----------------
| jiyik_id | jiyik_title | jiyik_author | submission_date |
---------- ---------------- -------------- -----------------
| 4 | 学习 python | 迹忆客 | 2018-03-08 |
| 5 | python3 教程 | jiyik.com | 2021-03-08 |
| 6 | redis 教程 | onmpw.com | 2021-03-08 |
| 1 | php 教程 | 迹忆客 | 2021-08-04 |
| 2 | mysql 教程 | 春天花开 | 2021-08-04 |
---------- ---------------- -------------- -----------------
5 rows in set (0.00 sec)
mysql> select * from jiyik_tbl order by submission_date desc;
---------- ---------------- -------------- -----------------
| jiyik_id | jiyik_title | jiyik_author | submission_date |
---------- ---------------- -------------- -----------------
| 1 | php 教程 | 迹忆客 | 2021-08-04 |
| 2 | mysql 教程 | 春天花开 | 2021-08-04 |
| 5 | python3 教程 | jiyik.com | 2021-03-08 |
| 6 | redis 教程 | onmpw.com | 2021-03-08 |
| 4 | 学习 python | 迹忆客 | 2018-03-08 |
---------- ---------------- -------------- -----------------
5 rows in set (0.01 sec)
mysql>
你可以使用php函数的mysqli query()或mysql_query()函数及相同的 sql select 带上 order by 子句的命令来获取数据。
该函数用于执行 sql 命令,然后通过 php 函数 mysqli_fetch_array() 来输出所有查询的数据。
$mysqli->query($sql,$resultmode)
参数 | 描述 |
---|---|
$sql | 必需。规定要使用的 mysql 连接。 |
resultmode | 可选。一个常量。可以是下列值中的任意一个: mysqli_use_result(如果需要检索大量数据,请使用这个) mysqli_store_result(默认) |
以下示例,查询后的数据按 jiyik_title 字段的升序排列后返回。
connect_errno ) {
printf("connect failed: %s\n", $mysqli->connect_error);
exit();
}
printf("connected successfully.\n");
$sql = "select jiyik_id, jiyik_title, jiyik_author, submission_date from jiyik_tbl order by jiyik_title asc";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
printf(
"id: %s, title: %s, author: %s, date: %d \n",
$row["jiyik_id"],
$row["jiyik_title"],
$row["jiyik_author"],
$row["submission_date"]
);
}
} else {
printf('no record found.\n');
}
mysqli_free_result($result);
$mysqli->close();
?>
结果如下:
connected successfully.
id: 4, title: 学习 python, author: 迹忆客, date: 2018
id: 2, title: mysql 教程, author: 春天花开, date: 2021
id: 1, title: php 教程, author: 迹忆客, date: 2021
id: 5, title: python3 教程, author: jiyik.com, date: 2021
id: 6, title: redis 教程, author: onmpw.com, date: 2021