简体   繁体   English

MYSQL 两列之和

[英]MYSQL SUM TWO COLUMNS

I have this situation:我有这种情况:

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

But not working because aliases cannot be used.但由于无法使用别名而无法正常工作。

Can you help me?你能帮助我吗?

Regards,问候,

You cannot use an alias defined in the same SELECT clause it is defined.您不能使用在其定义的同一SELECT子句中定义的别名。

You would need to repeat the expression:您需要重复表达式:

SUM(uto.points) + SUM(utl.points) AS total_points

If the SUM s may be NULL :如果SUM可能是NULL

COALESCE(SUM(uto.points), 0) + COALESCE(SUM(utl.points), 0) AS total_points

Alternatively, you can use a subquery:或者,您可以使用子查询:

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

Unrelated note: GROUP BY and SELECT * do not go along well together;无关说明: GROUP BYSELECT *不要 go 一起很好; it is a good practice to enumerate all non-aggregated columns in the GROUP BY clause (although MySQL is somewhat lax about it).GROUP BY子句中枚举所有非聚合列是一个好习惯(尽管 MySQL 对此有些松懈)。

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

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