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

2024-10-02 20:37:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题很简单,但要结束要花太多时间。我有一个数据库,其中有几个表,我需要检查的名称,也有一个变量,其中包含一个日期时间信息。但是每一张桌子我都花了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)

我有什么办法改进这个问题吗?我找不到任何有用的东西


Tags: ininfo数据库forexecutetablesindextime
1条回答
网友
1楼 · 发布于 2024-10-02 20:37:46

获取整个表fetchall()只是为了获取第一行的第一列tables_time_info[0][0],使用select中的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')

相关问题 更多 >