2016-11-07 19 views
0

私はMySQLで新しく、助けが必要です。私はスクリプトを書くためにMySQLのコネクタを使用しています。mysqlデータベースのすべてのテーブルをループする

私はデータベースを持っているが7Kのテーブルが含まれていると私は、これが一つのテーブル例えば(stats_20030103)のために働くこれらのテーブルの一部

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

からいくつかの値を選択しようとしています。しかし、私はすべてのテーブルのすべてのボリュームを合計したい.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はメタテーブルからの参加をサポートしていないかもしれません。その場合、あなたはそれを一時テーブルに選択するかもしれません。

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

MySQL doc on information_schema.tableを参照してください。

関連する問題