我需要一点帮助来简化我的mysql查询。我有三张桌子。一个用于主要用户记录,第二个用于每个用户的奖励积分(每个用户多个记录),第三个用于结果点(每个用户多个记录)。
SELECT u.*, (SELECT SUM(ub.Points)
FROM nba_user_bonus AS ub
WHERE ub.UserId = u.Id) AS BonusPoints,
(SELECT SUM(ur.Points)
FROM nba_user_result AS ur
WHERE ur.UserId = u.Id) AS ResultPoints
FROM nba_users AS u
WHERE u.Status = 'Enable'
ORDER BY u.Id ASC
这里我给每个用户提供总奖励积分和总积分,但是我需要通过TotalPoints DESC为每个用户订单设置TatalPoint(结果点和奖励积分的总和)。在排序中,我想要用户名单以获得排行榜的积分 请问我是否需要db表的任何进一步细节。 希望得到你的帮助。
答案 0 :(得分:1)
您的查询是合理的。您可以将两个值一起添加:
SELECT u.*,
((SELECT SUM(ub.Points) FROM nba_user_bonus ub WHERE ub.UserId = u.Id) +
(SELECT SUM(ur.Points) FROM nba_user_result ur WHERE ur.UserId = u.Id)
) as TotalPoints
FROM nba_users AS u
WHERE u.Status = 'Enable'
ORDER BY TotalPoints desc;
如果您需要所有三个值,可以使用子查询或重复计算:
SELECT u.*, (BonusPoints + ResultPoints) as TotalPoints
FROM (SELECT u.*,
(SELECT SUM(ub.Points) FROM nba_user_bonus ub WHERE ub.UserId = u.Id) as BonusPoints,
(SELECT SUM(ur.Points) FROM nba_user_result ur WHERE ur.UserId = u.Id) as ResultPoints
FROM nba_users AS u
WHERE u.Status = 'Enable'
) u
ORDER BY TotalPoints desc;
您也可以将此短语称为与group bys的连接。但是,select
中包含子查询的方法可能比该方法更快。
编辑:
要在第一种情况下处理NULL
,请使用ifnull()
或coalesce()
:
SELECT u.*,
(coalesce((SELECT SUM(ub.Points) FROM nba_user_bonus ub WHERE ub.UserId = u.Id), 0) +
coalesce((SELECT SUM(ur.Points) FROM nba_user_result ur WHERE ur.UserId = u.Id), 0)
) as TotalPoints
FROM nba_users AS u
WHERE u.Status = 'Enable'
ORDER BY TotalPoints desc;
答案 1 :(得分:0)
不要在语句的SELECT部分中进行子查询,而是使用连接。然后在末尾添加GROUP BY,以便获得不同的U.ID和UR和UB总计。
SELECT
u.ID,
SUM(ub.Points)+ SUM(ur.Points) as TotalPoints
FROM
nba_users AS u
LEFT OUTER JOIN nba_user_bonus as ub on
u.ID = ub.userid
LEFT OUTER JOIN nba_user_result as ur on
u.ID = ur.userid
WHERE u.STATUS = 'Enable'
GROUP BY 1
ORDER BY u.Id ASC