遍历 mysql 数据库中的所有表

loop over all tables in mysql databases

我是 MySQL 的新手,我需要一些帮助。我正在使用 MySQL 连接器来编写脚本。

我的数据库包含 7K tables,我正在尝试 select 来自其中一些 tables

的一些值
cursor.execute( "SELECT SUM(VOLUME) FROM stat_20030103 WHERE company ='Apple'")
for (Volume,) in cursor:
print(Volume)

这适用于一个 table,例如 (stats_20030103)。但是,我想对公司名称为 Apple 的所有 tables .startwith (stats_2016) 的所有音量求和。我如何循环我的 tables?

您或许可以使用 select * from information_schema.tables 将所有表名添加到您的查询中。

我不是 MySQL 方面的专家,但 python 中有一些快速简单的内容:

# Get all the tables starting with "stats_2016" and store them
cursor.execute("SHOW TABLES LIKE 'stats_2016%'")
tables = [v for (v, ) in cursor]

# Iterate over all tables, store the volumes sum
all_volumes = list()
for t in tables:
    cursor.execute("SELECT SUM(VOLUME) FROM %s WHERE company = 'Apple'" % t)
    # Get the first row as is the sum, or 0 if None rows found
    all_volumes.append(cursor.fetchone()[0] or 0)

# Return the sum of all volumes
print(sum(all_volumes))

我会尝试左连接。

SELECT tables.*, stat.company, SUM(stat.volume) AS volume 
    FROM information_schema.tables AS tables LEFT JOIN mydb.stat_20030103 AS stat 
    WHERE tables.schema = "mydb" GROUP BY stat.company;

这将立即为您提供所有结果。可能 MySQL 不支持从 metatables 加入,在这种情况下你可以 select 将它变成一个临时的 table.

CREATE TEMPORARY TABLE mydb.tables SELECT name FROM information_schema.tables WHERE schema = "mydb"

参见MySQL doc on information_schema.table