gpt4 book ai didi

python - 如何提高 Python 上 MySQL 查询的性能

转载 作者:行者123 更新时间:2023-11-29 09:37:57 26 4
gpt4 key购买 nike

我的查询非常简单,但需要太多时间才能结束。我有一个数据库,其中有几个表,我需要检查名称以及包含日期时间信息的变量。但对于每个表我花费了超过 100 秒。

query = "show tables"
cursor.execute(query)
tables_info = cursor.fetchall()

tables_info = [x[0] for x in tables_info]

time_month_year = []

for index in tqdm(range(len(tables_info))):
monthyearquery = "select tempo from {}".format(tables_info[index])
cursor.execute(monthyearquery)
tables_time_info = cursor.fetchall()
r = tables_time_info[0][0].strftime('%b %Y')
time_month_year.append(r)

有什么办法可以改进这个查询吗?我找不到任何有用的东西。

最佳答案

您正在获取整个表fetchall()只是为了获取第一行的第一列tables_time_info[0][0],请使用limit 1 在选择中使其仅返回一行。

time_month_year = []

for table_name in tables_info:
query = "select tempo from {} limit 1".format(tables_info)
cursor.execute(query)
tables_time_info = cursor.fetchall()
r = tables_time_info[0][0].strftime('%b %Y')
time_month_year.append(r)

请注意,您也可以使用 fetchone,但它不会带来性能提升,因为无论如何您只获取了 1 行,它只是更优雅

tables_time_info = cursor.fetchone()
r = tables_time_info[0].strftime('%b %Y')

关于python - 如何提高 Python 上 MySQL 查询的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57204922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com