首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MYSQL求和两列

问MYSQL求和两列
EN

Stack Overflow用户
提问于 2020-04-03 21:50:53
回答 1查看 41关注 0票数 1

我有这样的情况:

代码语言:javascript
复制
SELECT uf.*, SUM(uto.points) AS total_points_live, 
             SUM(utl.points) AS total_points_online,
             (total_points_live + total_points_online) AS total_points
FROM users AS uf    
            LEFT JOIN users_tourney_online AS uto
                ON uto.id_users = uf.id 
            LEFT JOIN users_tourney_live AS utl
                ON utl.id_users = uf.id
GROUP BY uf.id ORDER BY total_points DESC

但是不能工作,因为别名不能使用。

你能帮帮我吗?

致以敬意,

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-03 21:52:19

您不能使用在定义别名的同一SELECT子句中定义的别名。

您需要重复该表达式:

代码语言:javascript
复制
SUM(uto.points) + SUM(utl.points) AS total_points

如果SUM%s可以是NULL

代码语言:javascript
复制
COALESCE(SUM(uto.points), 0) + COALESCE(SUM(utl.points), 0) AS total_points

或者,您可以使用子查询:

代码语言:javascript
复制
SELECT t.*, coalesce(total_points_live, 0) + coalesce(total_points_online, 0) total_points
FROM (
    SELECT uf.*, SUM(uto.points) AS total_points_live, SUM(utl.points) AS total_points_online
    FROM ...
    GROUP BY uf.id
) t
ORDER BY total_points desc

不相关的说明:GROUP BY和SELECT *不能很好地配合使用;在GROUP BY子句中枚举所有非聚集列是一种很好的实践(尽管MySQL对此有点松懈)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61013431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档