如何在mysql中添加列值

27

这是我的表数据 Student

图片描述

这是我的查询语句 --

SELECT id, SUM( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`

但它只抛出一行——

id  total   maths   chemistry   physics
118     760     55  67  55

虽然我想对所有的id应用总和....请告诉我如何实现?

7个回答

72

Sum是一个聚合函数。您不需要使用它。这是一个简单的查询-

select *,(maths + chemistry + physics ) AS total FROM `student`

19

提示:如果其中一个字段可能为 NULL,则使用 COALESCE 将其默认为 0,否则 total 将会为 NULL。

SELECT *, (
    COALESCE(maths, 0) +
    COALESCE(chemistry, 0) +
    COALESCE(physics, 0)
) AS total 
FROM `student`

如果你想添加很多列,有没有比这更简单的方法?也许是数据库设置? - dasLort
@dasLort 考虑将您的表模式更改为 INT NOT NULL,例如默认值为 0? - digout

11
如果你需要获得每个学生的总分,则SUM不是你所需的。
SELECT id,
    (maths+chemistry+physics) AS total,
    maths,
    chemistry,
    physics
FROM `student`

完全可以胜任。


又一个迷人的答案..你们太棒了....对于学习者来说非常有帮助的平台 :) - Trialcoder

9
您不需要使用SUM进行此操作。尝试使用以下查询:
SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`

1
MySQL中的sum函数是指从选择语句中的列中给出值的总和。如果您需要对查询中的行进行求和,则只需使用加号(+)。您需要的是以下查询:
SELECT id, (`maths` +`chemistry`+`physics`) AS `total`, `maths`, `chemistry`, `physics`
FROM `student`;

这将为您提供所需的结果。

反引号在FROM之前是打错了吗? - Jimmmy

0

试试这个

SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`

你已经完成了。谢谢

0

所有的聚合函数都是针对由行名指定的行以及分组操作而工作的。你需要对单独的行执行操作,这对于任何聚合函数来说都不是选项。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接