当前位置:Gxlcms > 数据库问题 > Python MySQL Order By

Python MySQL Order By

时间:2021-07-01 10:21:17 帮助过:14人阅读


章节

  • Python MySQL 入门
  • Python MySQL 创建数据库
  • Python MySQL 创建表
  • Python MySQL 插入表
  • Python MySQL Select
  • Python MySQL Where
  • Python MySQL Order By
  • Python MySQL Delete
  • Python MySQL 删除表
  • Python MySQL Update
  • Python MySQL Limit
  • Python MySQL Join

对结果排序

可以使用ORDER BY语句,按升序或降序对结果排序。

默认情况下,ORDER BY关键字按升序排列结果。要按降序排列,可使用DESC关键字。

示例

name的字母顺序排列结果:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers ORDER BY name"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

ORDER BY DESC

使用DESC关键字,可按降序对结果排序。

示例

name的字母降序,对结果进行排序:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  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)

Python MySQL Order By

标签:创建表   code   hal   tps   import   http   name   int   passwd   

人气教程排行