排序
查询结果排序可以使用 ORDER BY 语句,默认的排序方式为升序,关键字为 ASC,如果要设置降序排序,可以设置关键字 DESC。
demo_mysql_test.py
按 name 字段字母的升序排序:
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()sql = "SELECT * FROM sites ORDER BY name"mycursor.execute(sql)myresult = mycursor.fetchall()forxinmyresult: print(x)
执行代码,输出结果为:
(3,'Github','https://www.github.com')
(2,'Google','https://www.google.com')
(1,'RUNOOB','https://www.runoob.com')
(5,'stackoverflow','https://www.stackoverflow.com/')
(4,'Taobao','https://www.taobao.com')
(6,'Zhihu','https://www.zhihu.com')
降序排序实例:
demo_mysql_test.py
按 name 字段字母的降序排序:
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()sql = "SELECT * FROM sites ORDER BY name DESC"mycursor.execute(sql)myresult = mycursor.fetchall()forxinmyresult: print(x)
执行代码,输出结果为:
(6,'Zhihu','https://www.zhihu.com')
(4,'Taobao','https://www.taobao.com')
(5,'stackoverflow','https://www.stackoverflow.com/')
(1,'RUNOOB','https://www.runoob.com')
(2,'Google','https://www.google.com')
(3,'Github','https://www.github.com')