当前位置:首页 > python教程 > python基础

Python MySQL Order By

  • mysql where

结果排序

请使用 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

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!