使用 Python 对 MySql 表的列进行排序 [英] Ordering the columns of MySql table using Python
问题描述
我是 SQL 初学者.
I'm beginner in SQL.
考虑我的简单代码:
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1', database='employees')
cursor = cnx.cursor()
cursor.execute('SELECT * FROM people ORDER BY Height DESC, Weight')
my_result = cursor.fetchall()
cnx.close()
for x in my_result:
print(x[0], x[1], x[2])
我的 employees 数据库中有一个 people 表,其中包含 name、Height 和 Weight 列.如果我运行此代码,它会打印所需的排序并且没有问题.但是,这段代码似乎并没有改变表格行的顺序.我的意思是,现在如果我跑
I have a people table in my employees database with columns name, Height and Weight. If I run this code, it prints the desired sorting and there's no problem. But, it seems that this code essentially doesn't change the order of rows of the table. I mean, now if I run
SELECT * FROM people;
在终端中,我得到后一个表(没有所需的顺序).现在,我的问题是:
in terminal I get the latter table (which does not have the desired order). Now, my question is:
如何更改表格的顺序以使用 Python 获得具有所需排序的新表格?有可能吗?
How can I change the order of the table to obtain a new table with desired sorting using Python? Is it possible?
谢谢.
推荐答案
您可以像旧表一样创建一个新表并按所需顺序插入行,否则始终使用 ORDER BY 运行查询.
You can create a new table like the old one and insert rows with the desired order, otherwise always run your query with ORDER BY.
要创建新表,您可以运行类似于以下内容的查询:
To create a new table you can run a query similar to:
CREATE TABLE people_sorted LIKE people;
INSERT people_sorted SELECT * FROM people ORDER BY Height DESC, Weight;
这篇关于使用 Python 对 MySql 表的列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!