Python MySQL 排序
对结果进行排序
使用
ORDER BY
语句按升序或降序对结果进行排序。
ORDER BY
关键字默认(
ASC
)对结果进行升序排序。如要按降序排序使用
DESC
关键字。
实例
按名称的字母顺序排序:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="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命令
使用
DESC
关键字按降序排序
实例
按名称按字母从z~a排序:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="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)
运行实例 »