简体   繁体   中英

MySQL - Adding row total across multiple columns

I have a MySQL table with about 100 columns. All columns are INT. I want to be able to select a row by its ID, and get the total number of all of the columns added together.

There are two additional considerations. The field titles vary significantly, so I would like to be able to have it work by referencing the field number, rather than the field title.

Lastly, I would like to potentially be able to specify a range, for example, add total of field 35 through field 76 where id = 50.

Is there a way to do this? Thank you very much!

You need to build dynamically a query.

First thing you need the column names (you can retrieve them automatically too, but need an extra query). Best thing is to put them in a array:

$Fields = array(
   'id', 'fld2', 'fld3', ..., 'fld99'
);

function getSumField($from, $to, $allow_null = False)
{
    GLOBAL $Fields;
    $a_sum = array();
    for($i = $from; $i <= $to; $i++)
    {
        if ($allow_null)
            $a_sum[] = "COALESCE({$Fields[$i]},0)";
        else
            $a_sum[] = $Fields[$i];
    }
    return '('.implode('+', $a_sum).')';
}

// So we want: sum of fields 17-42 of the ONE ROW where ID = 5

$fld = getSumField(17, 42);
$SQL = "SELECT $fld FROM tbl WHERE id = 5;";

// Sum of same, in rows with ids from 7 to 22
$SQL = "SELECT SUM($fld) AS total FROM tbl WHERE id BETWEEN 7 AND 22;";

You can get a list of columns using the info_schema:

select * from information_schema.columns where table_name='table'

Using that you could build an array of columns, make your query and sum the values. Its not quite a 'one step' process but it would suffice.

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