使用 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)
运行示例 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!