0

我需要对除第一列之外的一行的总数求和。
也有类似的东西:

从数字中选择总和(col2 + col3 + col4 +colN),其中 user_name = 'person';

我的表将不断添加列。所以我希望它也自动获取新列的总和,而无需将其硬编码到查询中?

user_name  | Col | col2 | Col3 | Col4 + other columns.

person1    |  2  |  3   | 76   | 56  etc.    ---------> sum of row

person2    |  6  |  72  | 200  | 13  etc.    ---------> sum of row

提前感谢您的帮助!

4

3 回答 3

3

不希望“避免”这个问题,但看起来你可以使用不同的数据结构。

您应该考虑创建一个包含idand列的“用户”表user_name,以及一个新表(例如properties),在当前表(Col1, Col2... ColN)中的每个其他列都有一行。然后,新表将有一个 user_name 列,以将其链接到 users 表。

这样你就可以做类似的事情:

SELECT SUM(property_column) FROM properties WHERE user_name = <RequiredUserName>

我还建议按 ID 选择用户(即,让properties表带有 user_id 列,而不是 user_name 列),除非您确信 user_name 永远不会改变(即使那样......)。

于 2012-04-23T12:16:58.793 回答
1

也许最简单的解决方案是在 PHP 中进行:

$res = mysql_query("select * from numbers where user = ...");
while ($row = mysql_fetch_assoc($res)) {
    $row['Id'] = 0; // don't want to sum the Id
    $sum = array_sum($row); // this is the required sum
    ....
}
于 2012-04-23T12:23:36.117 回答
0

如前所述,您最好重新访问您的数据库结构,如果您不能并且如果您想在 PHP 中执行此操作,您可以获取结果集,然后循环遍历字段并排除您不想要的字段,然后添加其他一切,假设它是正确的类型,使用 mysql_field_type 来查找特定类型的那些。

于 2012-04-23T12:17:10.953 回答