Python MySQL ORDER BY
-
排序结果
使用ORDER BY语句对结果进行升序或降序排序。默认情况下,ORDER BY关键字对结果进行升序排序。要按降序对结果进行排序,请使用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关键字以降序对结果进行排序。按名称的字母顺序对结果进行反向排序:
尝试一下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)