2016-11-07 942 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