按每个user_id下降

时间:2015-06-30 12:05:06

标签: mysql group-by sql-order-by

select 
((select 
        COALESCE(sum(b.points_received), 0) as badge_total_points
    from
        user_badges ub
            join
        badges b ON ub.badge_id = b.badge_id
    where
        ub.user_id = '$user_id') + (select 
        COALESCE(sum(aps.given_points), 0) as total_action_points
    from
        user_action_points uap
            join
        action_point_system aps ON uap.point_id = aps.point_id
    where
        uap.user_id = '$user_id')) as total_contribution_points

如何使用此SQL语句检索列表,以获取user_id分组的总点数?有人有建议吗?

编辑:

select 
ub.user_id,
COALESCE(sum(b.isGold), 0) as gold_count,
COALESCE(sum(b.isSilver), 0) as silver_count,
COALESCE(sum(b.isBronze), 0) as bronze_count
from
user_badges ub
    join
badges b ON ub.badge_id = b.badge_id
group by ub.user_id

如何将此查询添加到第一个问题的结果中?

1 个答案:

答案 0 :(得分:0)

尽管有多种方法可以执行您想要的操作,但您可以使用相关子查询构建现有查询:

select u.*,
       ((select COALESCE(sum(b.points_received), 0) as badge_total_points
         from user_badges ub join
              badges b
              ON ub.badge_id = b.badge_id
         where ub.user_id = u.user_id
        ) +
        (select COALESCE(sum(aps.given_points), 0) as total_action_points
         from user_action_points uap join
              action_point_system aps
              ON uap.point_id = aps.point_id
         where uap.user_id = u.user_id
        )
       ) as total_contribution_points
from users u
order by total_contribution_points desc;