1

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,

1
  • 1 column group by may produce indeterminate columns when you select * and is illegal in most sql dialects when there are more non aggregate columns in the select clause than the group by. And there is a good chance you may trip up on this if you ever upgrade or have an environment where 'only_full_group_by' is set. Commented Apr 3, 2020 at 13:56

1 Answer 1

3

You cannot use an alias defined in the same SELECT clause it is defined.

You would need to repeat the expression:

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

If the SUMs may be 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; it is a good practice to enumerate all non-aggregated columns in the GROUP BY clause (although MySQL is somewhat lax about it).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.