Python MySQL Order By
- 上一頁 MySQL Where
- 下一頁 MySQL Delete
結果排序
請使用 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)
- 上一頁 MySQL Where
- 下一頁 MySQL Delete