MySQL (20) --- sort

Sort MySQL

We know that to read the data using SQL SELECT statement from the MySQL table.

If we need to sort of read data, we can use the MySQL  ORDER BY  clause according to which you want to set a field which way to sort, and then returned in the search results.

grammar

The following is a SQL SELECT statement ORDER BY clause to sort query data and then return the data:

Field1 the SELECT, Field2, ... fieldN table_name1, table_name2 ... 
the ORDER BY field1 [ASC [DESC] [Default ASC]], [field2 ...] [ASC [DESC] [ Default ASC]]
  • You can use any sort of field as a condition, to return query results sorted.
  • You can set multiple fields to sort.
  • You can use the ASC or DESC keyword to set the query results in ascending or descending order. By default, it is ascending.
  • You can add WHERE ... LIKE clause to set conditions.

At the command prompt using the ORDER BY clause

The following will use the ORDER BY clause in the SQL SELECT statement to read data in MySQL data tables runoob_tbl:

Examples

Try following examples, the results are ordered in ascending and descending order.

SQL Sorting

mysql> use RUNOOB;
Database changed
mysql> SELECT * from runoob_tbl ORDER BY submission_date ASC;
+-----------+---------------+---------------+-----------------+
| 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      |
+-----------+---------------+---------------+-----------------+
4 rows in set (0.01 sec)
 
mysql> SELECT * from runoob_tbl ORDER BY submission_date DESC;
+-----------+---------------+---------------+-----------------+
| 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      |
+-----------+---------------+---------------+-----------------+
4 rows in set (0.01 sec)

Runoob_tbl read all the data in the table in ascending order in accordance submission_date field.

Guess you like

Origin blog.csdn.net/zhangbijun1230/article/details/92383263