I have a MySQL database called “bookfeather.” It contains 56 tables. Each table has the following structure:
id site votes_up votes_down
The value for “site” is a book title. The value for “votes_up” is an integer. Sometimes a unique value for “site” appears in more than one table.
For each unique value “site” in the entire database, I would like to sum “votes_up” from all 56 tables. Then I would like to print the top 25 values for “site” ranked by total “votes_up”.
How can I do this in PHP?
Thanks in advance,
John
Here’s a PHP code snip that should get it done.
I have not tested it so it might have some typos and stuff, make sure you replace DB_NAME
$result = mysql_query("SHOW TABLES"); $tables = array(); while ($row = mysql_fetch_assoc($result)) { $tables[] = '`'.$row["Tables_in_DB_NAME"].'`'; } $subQuery = "SELECT site, votes_up FROM ".implode(" UNION ALL SELECT site, votes_up FROM ",$tables); // Create one query that gets the data you need $sqlStr = "SELECT site, sum(votes_up) sumVotesUp FROM ( ".$subQuery." ) subQuery GROUP BY site ORDER BY sum(votes_up) DESC LIMIT 25"; $result = mysql_query($sqlStr); $arr = array(); while ($row = mysql_fetch_assoc($result)) { $arr[] = $row["site"]." - ".$row["sumVotesUp"]; } print_r($arr)