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)
运行示例 »
ORDER BY DESC
使用 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)
运行示例 »