1、对结果排序
使用ORDER BY语句对结果进行升序或降序排序。
默认情况下,ORDER BY关键字对结果进行升序排序。 要按降序对结果进行排序,请使用DESC关键字。
例如:
按名称的字母顺序对结果进行排序:result:
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)
2、降序排序(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)