mysql - 使数千个 SELECT 查询更快

标签 mysql mariadb pymysql

情况

  • 使用 Python 3.7.2
  • 我已阅读过服务器上具有 5M 行的 MariaDB 表的特权。
  • 我有一个包含 7K 整数的本地文本文件,每行一个。
  • 整数代表表的 IDX。
  • 表的 IDX 列是主键。 (所以我想它会自动索引?)

问题

我需要选择 IDX 位于文本文件中的所有行。

我的努力

版本 1

进行 7K 次查询,文本文件中的每一行一个查询。这使得每秒大约 130 个查询,大约需要 1 分钟才能完成。

import pymysql
connection = pymysql.connect(....)
with connection.cursor() as cursor:
    query = (
        "SELECT *"
        " FROM TABLE1"
        " WHERE IDX = %(idx)s;"
    )

    all_selected = {}
    with open("idx_list.txt", "r") as f:
        for idx in f:
            idx = idx.strip()
            if idx:
                idx = int(idx)
                parameters = {"idx": idx}
                cursor.execute(query, parameters)
                result = cursor.fetchall()[0]
                all_selected[idx] = result

版本 2

选择整个表,迭代光标并挑选行。 .fetchall_unbuffered() 上的 for 循环每秒处理 30-40K 行,整个脚本大约需要 3 分钟才能完成。

import pymysql
connection = pymysql.connect(....)
with connection.cursor() as cursor:
    query = "SELECT * FROM TABLE1"

    set_of_idx = set()
    with open("idx_list.txt", "r") as f:
        for line in f:
            if line.strip():
                line = int(line.strip())
                set_of_idx.add(line)


    all_selected = {}
    cursor.execute(query)
    for row in cursor.fetchall_unbuffered():
        if row[0] in set_of_idx:
            all_selected[row[0]] = row[1:]

预期行为

我需要更快地选择,因为文本文件中的 IDX 数量将来会增长到 10K-100K。

我查阅了其他答案,包括this ,但我无法使用它,因为我只有读取权限,因此无法创建另一个表来加入。

那么如何才能更快地进行选择呢?

最佳答案

临时表的实现如下所示:

connection = pymysql.connect(....,local_infile=True)
with connection.cursor() as cursor:
    cursor.execute("CREATE TEMPORARY TABLE R (IDX INT PRIMARY KEY)")
    cursor.execute("LOAD DATA LOCAL INFILE 'idx_list.txt' INTO R")
    cursor.execute("SELECT TABLE1.* FROM TABLE1 JOIN R USING ( IDX )")
    ..
    cursor.execute("DROP TEMPORARY TABLE R")

关于mysql - 使数千个 SELECT 查询更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54900574/

相关文章:

python - 使用 Anaconda 安装本地包

mysql - 向现有 MySQL 表添加包含表名 + 增量的列

mysql - 5.5.52-MariaDB 与 5.6.15 mysql 触发器不工作

java - 将 mariaDB 客户端与 MySQL 数据库集成的问题

python - InternalError : (pymysql. err.InternalError) (1193, "Unknown system variable ' transaction_isolation'")

python - pyMySQL:如何检查连接是否已经打开或关闭

mysql - SELECT 和其他值的 INSERT 结果

mysql - 如何通过mysql查询从考勤表中获取月度考勤报告?

php - 如何使用 php 从 url 保存图像并替换(如果已存在)

javascript - 使用nodejs从MariaDB获取数据并将其发送到html页面(Express JS)