2016-11-07 81 views
0

我是MySQL新手,我需要一些帮助。我正在使用MySQL连接器来编写脚本。循环遍历mysql数据库中的所有表

我有数据库包含7K表,我试图从一些这些表

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

这适用于一个表e.g(stats_20030103)的选择一些值。不过,我想总结所有表格.startwith(stats_2016),其中公司名称是Apple。我如何在我的桌子上循环播放?

+1

尝试执行''SHOW TABLES''并玩这个结果。 –

回答

0

您可以使用select * from information_schema.tables将所有表名称放入查询中。

0

我不是在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)) 
0

我想尝试左加入。

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进行连接,在这种情况下,您可能会将其选择到临时表中。

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

参见MySQL doc on information_schema.table