目录

Python MySQL 排序


对结果排序

使用 ORDER BY 语句对结果进行升序或降序排序。

ORDER BY 关键字默认对结果进行升序排序。要按降序对结果进行排序,请使用 DESC 关键字。

示例

按名称字母顺序对结果进行排序: 结果:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user=" yourusername",
  password=" yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers ORDER BY name"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)
运行示例 »

按描述排序

使用 DESC 关键字对结果进行降序排序。

示例

按名称字母顺序对结果进行反向排序:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user=" yourusername",
  password=" yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers ORDER BY name DESC"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)
运行示例 »