请使用 ORDER BY 语句按升序或降序对结果进行排序。
ORDER BY 关键字默认按升序对结果进行排序。若要按降序对结果进行排序,请使用 DESC 关键字。
以字符顺序对姓名进行排序,结果:
import mysql.connectormydb = 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 关键字按降序对结果进行排序。
按反转字母顺序对姓名的结果进行排序:
import mysql.connectormydb = 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)