简体   繁体   中英

How to get grand total of many tables' totals

I have 500 tables, all containing records of dollar amounts in the field "sales".

The following gets me the total sales of green items per table:

$tabletotal = mysql_query("SELECT sum(sales) FROM databasename.$tablename
WHERE type = 'green' AND descr  LIKE '%SOLD%'   ");
$row = mysql_fetch_assoc($tabletotal);
$answer= $row['sum(sales)'];

So if a particular table has 4 green items and they were sold for $4, $6, $7, and $3, then the answer I get above is $20.

Now, what I don't know how to do, is to get the total of all green items in ALL 500 tables. So if table 1 has a total of $20, table 2 a total of $36, table 3 a total of $15, and so on, I want to get the grand total in all tables together (in this case $71 but it would be more for 500 tables obviously).

Any help anyone?

Probably best to use a for loop:

$tables = array('tbl1', 'tbl2', 'tbl3', ..., 'tbl499');
$total = 0;
foreach ($tables as $t)
{
    $tabletotal = mysql_query("SELECT sum(sales) tot FROM databasename.$t WHERE type = 'green' AND descr LIKE '%SOLD%'");
    $row = mysql_fetch_assoc($tabletotal);
    $total += $row['tot'];
}

Alternatively, you could generate a giant SQL query using UNION s, but it's essentially the same thing.

As Dream Eater mentions; you shouldn't be in this situation in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM