MySQL - ORDER BY 子句



MySQL ORDER BY 子句

MySQL 的ORDER BY 子句用于按提供的顺序对表的列进行排序,该顺序可以是升序或降序。如果未指定排序顺序,则默认情况下,它按升序对列进行排序。

排序使用两个关键字指定;ASC 表示升序,DESC 表示降序。

使用 ORDER BY 子句,我们可以对表的多个列进行排序,并为每一列提供不同的排序顺序。例如,我们可以先按一列排序结果集,然后按另一列排序,以此类推。

语法

以下是 MySQL 中 ORDER BY 子句的语法:

SELECT column-list
FROM table_name
[ORDER BY column1, column2, ..., columnN] [ASC|DESC]

这里:

  • column-list 是我们要从 table_name 中检索的列的名称。

  • column1, column2,...columnN 是我们要排序的列。

  • ASC 将对列进行升序排序。

  • DESC 将对列进行降序排序。

默认情况下,ORDER BY 子句按升序对提供的列进行排序。

示例

首先,让我们使用以下查询创建一个名为CUSTOMERS 的表:

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR (20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),       
   PRIMARY KEY (ID)
);

以下查询将 7 条记录插入到上面创建的表中:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

执行以下查询以验证 CUSTOMERS 表是否已创建:

Select * from CUSTOMERS;

CUSTOMERS 表已成功创建:

ID 姓名 年龄 地址 工资
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

现在,让我们显示 CUSTOMERS 表中的所有列,按 NAME 列排序:

默认情况下,ORDER BY 子句按升序对提供的列进行排序。

SELECT * FROM CUSTOMERS
ORDER BY NAME;

输出

从下面的输出中可以看到,NAME 列按升序排序。

ID 姓名 年龄 地址 工资
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
3 Kaushik 23 Kota 2000.00
2 Khilan 25 Delhi 1500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00
1 Ramesh 32 Ahmedabad 2000.00

ORDER BY with DESC

我们可以使用 ORDER BY 子句和 DESC 关键字将表的特定列按降序排序。让我们通过以下示例来了解。

示例

在以下查询中,我们显示 CUSTOMERS 表中的所有列,按 NAME 列降序排序:

SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

输出

从下面的输出中可以看到,NAME 列按降序排序。

ID 姓名 年龄 地址 工资
1 Ramesh 32 Ahmedabad 2000.00
7 Muffy 24 Indore 10000.00
6 Komal 22 Hyderabad 4500.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
4 Chaitali 25 Mumbai 6500.00

ORDER BY with 多列

我们还可以对 MySQL 表的多个列进行排序。为此,我们需要在 ORDER BY 子句中指定所有列名。

示例

在这里,我们选择 CUSTOMERS 表中的所有列,按 ADDRESS 和 NAME 列排序。

SELECT * FROM CUSTOMERS
ORDER BY ADDRESS, NAME;

输出

上述查询首先按升序对 ADDRESS 列进行排序,对于具有相同 ADDRESS 值的任何行,它们将按 NAME 列升序排序。

这意味着所有具有相同 ADDRESS 值的行将分组在一起并按 NAME 排序。

ID 姓名 年龄 地址 工资
1 Ramesh 32 Ahmedabad 2000.00
5 Hardik 27 Bhopal 8500.00
2 Khilan 25 Delhi 1500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00

ORDER BY with ASC 和 DESC

在 MySQL 中,我们可以在同一个查询中按ASCDESC 对列进行排序。首先提供的带有 ASC 的列将按升序排序,第二个提供的带有 DESC 的列将按降序排序。

示例

在这个查询中,我们选择 CUSTOMERS 表中的所有列,按 AGE 升序排序,按 SALARY 降序排序:

SELECT * FROM CUSTOMERS
ORDER BY AGE ASC, SALARY DESC;

输出

执行给定程序后,输出如下所示:

ID 姓名 年龄 地址 工资
6 Komal 22 Hyderabad 4500.00
3 Kaushik 23 Kota 2000.00
7 Muffy 24 Indore 10000.00
4 Chaitali 25 Mumbai 6500.00
2 Khilan 25 Delhi 1500.00
5 Hardik 27 Bhopal 8500.00
1 Ramesh 32 Ahmedabad 2000.00

ORDER BY with LENGTH()

我们可以将LENGTH() 函数与 MySQL 中的 ORDER BY 子句一起使用,以根据特定列中存在的长度对值进行排序。

示例

使用以下查询,我们根据长度对 ADDRESS 列进行排序:

SELECT * FROM CUSTOMERS
ORDER BY LENGTH(ADDRESS) ASC;

输出

上面程序的输出如下所示:

ID 姓名 年龄 地址 工资
3 Kaushik 23 Kota 2000.00
2 Khilan 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00
1 Ramesh 32 Ahmedabad 2000.00
6 Komal 22 Hyderabad 4500.00

使用客户端程序的 Order By 子句

除了使用 MySQL ORDER BY 子句对表的列进行排序外,我们还可以使用 Node.js、PHP、Java 和 Python 等客户端程序来实现相同的结果。

语法

以下是各种编程语言中此操作的语法:

要通过 PHP 程序对 MySQL 表的一列或多列进行排序,我们需要使用mysqli 函数query() 执行带有 ORDER BY 子句的 SELECT 语句,如下所示:

$sql = "SELECT COLUMN1, COLUMN2, .. FROM TABLE_NAME 
ORDER BY COLUMN1, COLUMN2, ... ASC|DESC";
$mysqli->query($sql);

要通过 Node.js 程序对 MySQL 表格中的一列或多列进行排序,我们需要使用 **mysql2** 库的 **query()** 函数执行包含 ORDER BY 子句的 SELECT 语句,如下所示:

sql= SELECT column-list FROM table_name
[ORDER BY column1, column2, ..., columnN] [ASC|DESC]  
con.query(sql);

要通过 Java 程序对 MySQL 表格中的一列或多列进行排序,我们需要使用 **JDBC** 的 **executeUpdate()** 函数执行包含 ORDER BY 子句的 SELECT 语句,如下所示:

String sql = "SELECT column-list FROM table_name 
[ORDER BY column1, column2, ..., columnN] [ASC|DESC]";
statement.executeQuery(sql);

要通过 Python 程序对 MySQL 表格中的一列或多列进行排序,我们需要使用 MySQL **Connector/Python** 的 **execute()** 函数执行包含 ORDER BY 子句的 SELECT 语句,如下所示:

order_by_clause_query = SELECT column-list FROM table_name 
[ORDER BY column1, column2, ..., columnN] [ASC|DESC]
cursorObj.execute(order_by_clause_query);

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
   printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = 'SELECT * from tutorials_tbl ORDER BY tutorial_author ASC'; $result = $mysqli->query($sql); if ($result->num_rows > 0) { printf("Table records based on 'tutorial_author' in ascending order: \n"); while($row = $result->fetch_assoc()) { printf("ID %d, Title: %s, Author: %s ", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"]); printf("\n"); } } else { printf('No record found.
'); } mysqli_free_result($result); $mysqli->close();

输出

获得的输出如下所示:

Table records based on 'tutorial_author' in ascending order:
ID 5, Title: Learn MySQL, Author: Abdul S
ID 4, Title: Learn PHP, Author: John Poul
ID 2, Title: PHP Tut, Author: New Author
ID 1, Title: Java Tutorial, Author: new_author
ID 3, Title: JAVA Tutorial, Author: Sanjay          
var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  //Creating a Database
  sql = "create database TUTORIALS"
  con.query(sql);

  //Select database
  sql = "USE TUTORIALS"
  con.query(sql);

  //Creating table
  sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID));"
  con.query(sql);

  //Inserting Records
  sql = "INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS, SALARY) VALUES(1,'Ramesh', 32, 'Hyderabad', 2000.00),(2,'Khilan', 25, 'Delhi', 1500.00),(3,'kaushik', 23, 'Hyderabad', 2000.00),(4,'Chaital', 25, 'Mumbai', 6500.00),(5,'Hardik', 27, 'Vishakapatnam', 8500.00),(6, 'Komal',22, 'Vishakapatnam', 4500.00),(7, 'Muffy',24, 'Indore', 10000.00);"
  con.query(sql);

  //Using ORDER BY Clause
  sql = "SELECT * FROM CUSTOMERS ORDER BY NAME;"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log(result)
  });
});               

输出

生成的输出如下所示:

Connected!
--------------------------
[
  {
    ID: 4,
    NAME: 'Chaital',
    AGE: 25,
    ADDRESS: 'Mumbai',
    SALARY: '6500.00'
  },
  {
    ID: 5,
    NAME: 'Hardik',
    AGE: 27,
    ADDRESS: 'Vishakapatnam',
    SALARY: '8500.00'
  },
  {
    ID: 3,
    NAME: 'kaushik',
    AGE: 23,
    ADDRESS: 'Hyderabad',
    SALARY: '2000.00'
  },
  {
    ID: 2,
    NAME: 'Khilan',
    AGE: 25,
    ADDRESS: 'Delhi',
    SALARY: '1500.00'
  },
  {
    ID: 6,
    NAME: 'Komal',
    AGE: 22,
    ADDRESS: 'Vishakapatnam',
    SALARY: '4500.00'
  },
  {
    ID: 7,
    NAME: 'Muffy',
    AGE: 24,
    ADDRESS: 'Indore',
    SALARY: '10000.00'
  },
  {
    ID: 1,
    NAME: 'Ramesh',
    AGE: 32,
    ADDRESS: 'Hyderabad',
    SALARY: '2000.00'
  }
]         
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class OrderByClause {
  public static void main(String[] args) {
    String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
    String user = "root";
    String password = "password";
    ResultSet rs;
    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            String sql = "SELECT * FROM CUSTOMERS ORDER BY NAME DESC";
            rs = st.executeQuery(sql);
            System.out.println("Table records(in DESC order): ");
            while(rs.next()){
              String id = rs.getString("Id");
              String name = rs.getString("Name");
              String age = rs.getString("Age");
              String address = rs.getString("Address");
              String salary = rs.getString("Salary");
              System.out.println("Id: " + id +", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary);
            }
    }catch(Exception e) {
      e.printStackTrace();
    }
  }
}                             

输出

获得的输出如下所示:

Table records(in DESC order): 
Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00
Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00
Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00         
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
# Creating a cursor object 
cursorObj = connection.cursor()
order_by_clause_query = """
SELECT *
FROM customers
ORDER BY AGE ASC
"""
cursorObj.execute(order_by_clause_query)
# Fetch all the ordered rows
ordered_rows = cursorObj.fetchall()
# Printing the ordered rows
for row in ordered_rows:
    print(row)
cursorObj.close()
connection.close()                                         

输出

以下是上述代码的输出:

(3, 'kaushik', 23, 'Hyderabad', Decimal('11000.00'))
(7, 'Muffy', 24, 'Delhi', Decimal('10000.00'))
(2, 'Khilan', 25, 'Kerala', Decimal('8000.00'))
(4, 'Chaital', 25, 'Mumbai', Decimal('1200.00'))
(5, 'Hardik', 27, 'Vishakapatnam', Decimal('10000.00'))
(6, 'Komal', 29, 'Vishakapatnam', Decimal('7000.00'))
(1, 'Ramesh', 32, 'Hyderabad', Decimal('4000.00'))  
广告