简体   繁体   English

MySQL-跨多列添加行总数

[英]MySQL - Adding row total across multiple columns

I have a MySQL table with about 100 columns. 我有一个约100列的MySQL表。 All columns are INT. 所有列均为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. 我希望能够通过其ID选择一行,并获得加在一起的所有列的总数。

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. 最后,我希望能够指定一个范围,例如,将字段35到ID = 50的字段76的总数相加。

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: 您可以使用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. 这虽然不是一个“一步”的过程,但足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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