标题: MySQL 数据库查询与数据操作:使用 ORDER BY 排序和 DELETE 删除记录 [打印本页] 作者: 农妇山泉一亩田 时间: 2023-12-15 07:57 标题: MySQL 数据库查询与数据操作:使用 ORDER BY 排序和 DELETE 删除记录 使用 ORDER BY 进行排序
使用 ORDER BY 语句按升序或降序对结果进行排序。
ORDER BY 关键字默认按升序排序。要按降序排序结果,使用 DESC 关键字。
示例按名称按字母顺序排序结果:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="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)
复制代码
ORDER BY DESC
使用 DESC 关键字以降序排序结果。
示例按名称以字母逆序排序结果:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name DESC"