2016-11-07 5 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) 

의 일부에서 일부 값을 선택하려합니다. 그러나 회사 이름이 Apple 인 모든 테이블 .startwith (stats_2016)의 모든 볼륨을 합산하려고합니다. 테이블을 어떻게 반복 할 수 있습니까?

+1

'SHOW TABLES'를 실행하고 그 결과로 실행 해보십시오. –

답변

0

쿼리에 모든 테이블 이름을 가져 오려면 select * from information_schema.tables을 사용할 수 있습니다.

0

나는 MySQL의 전문가는 아니지만 여기 파이썬에서 빠르고 간단하게 뭔가 :

# 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을 참조하십시오.