Mysql在新查询中使用查询结果

时间:2016-07-25 02:46:38

标签: mysql

所以我有两个名为points_log的表和一个名为leaderboard的表。

mysql> describe points_log;
+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| user_id | int(11) | NO   |     | NULL    |       |
| points  | int(11) | YES  |     | 0       |       |
| date    | date    | NO   |     | NULL    |       |
+---------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> describe leaderboard;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| bucket    | varchar(255) | YES  |     | NULL    |       |
| user_id   | int(11)      | YES  |     | NULL    |       |
| school_id | int(11)      | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

我有以下查询:

 SELECT leaderboard.user_id FROM leaderboard where 
 leaderboard.bucket=(SELECT bucket FROM leaderboard WHERE leaderboard.user_id=$user_id) AND
 leaderboard.school_id = (SELECT school_id FROM leaderboard WHERE leaderboard.user_id=$user_id)

这将返回包含$ user_id传入的存储桶中的user_id的一行或多行。我想要做的就是获取所有这些user_id并查找运行以下查询

SELECT sum(points) FROM points_log WHERE user_id=$user_id AND 
date >= (SELECT subdate(curdate(), INTERVAL (weekday(now())) DAY))

问题是这第二个查询如果不能保证返回一些东西,那么在它没有返回任何我希望sum(points)为0的情况下。我还需要返回user_id,bucket和每行的总和(点数)。

现在我拥有的是

SELECT leaderboard.user_id,sum(points_log.points) AS points, leaderboard.bucket
        FROM points_log LEFT JOIN leaderboard ON points_log.user_id = leaderboard.user_id
        WHERE points_log.DATE >= (SELECT subdate(curdate(), INTERVAL (weekday(now())) DAY))
        AND leaderboard.bucket=(SELECT bucket FROM leaderboard WHERE leaderboard.user_id=$user_id)
        AND leaderboard.school_id = (SELECT school_id FROM leaderboard WHERE leaderboard.user_id=$user_id)
        GROUP BY USER_ID ORDER BY SUM(points) DESC

这个问题是它只有在该用户的points_log中有值时才有效。如果没有价值,我不确定如何将其默认设为0.

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

SELECT leaderboard.user_id, COALESCE( sum(points_log.points), 0 )AS points, leaderboard.bucket 
FROM points_log RIGTH OUTER JOIN leaderboard ON points_log.user_id = leaderboard.user_id 
WHERE points_log.DATE >= (SELECT subdate(curdate(), INTERVAL (weekday(now())) DAY)) 
AND leaderboard.bucket=(SELECT bucket FROM leaderboard WHERE leaderboard.user_id=$user_id) 
AND leaderboard.school_id = (SELECT school_id FROM leaderboard WHERE leaderboard.user_id=$user_id) 
GROUP BY USER_ID ORDER BY SUM(points) DESC 

试试这个...请注意Outer JoinCOALESCE功能。