这个查询
SELECT u.username,
SUM(p.likes) AS likePoints1,
SUM(p2.likes)*2 AS likePoints2
FROM users as u
LEFT JOIN (SELECT recommendedByUserId as rid, id as ruid from users WHERE created >= DATE('2013-09-16') AND created <= DATE('2013-09-30')) AS r ON r.rid = u.id
LEFT JOIN (SELECT * FROM posts WHERE created >= DATE('2013-09-16') AND created <= DATE('2013-09-30')) AS p ON p.author_id = ruid
LEFT JOIN (SELECT * FROM posts WHERE created >= DATE('2013-09-16') AND created <= DATE('2013-09-30')) AS p2 ON p2.author_id = u.id
GROUP BY u.id
在“likePoints2”列上给出错误的结果,而这
SELECT u.username,
SUM(p2.likes)*2 AS likePoints2
FROM users as u
LEFT JOIN (SELECT * FROM posts WHERE created >= DATE('2013-09-16') AND created <= DATE('2013-09-30')) AS p2 ON p2.author_id = u.id
GROUP BY u.id
是完全正确的。
问题是,我需要总结给定日期范围内 posts.author_id = current u.id 上的所有 posts.likes。
我会很感激任何意见!
测试数据
用户
id | recommendedByUserId
1 | 3
2 | 3
3 | NULL
4 | 1
帖子
author_id | likes
1 | 5
3 | 2
4 | 1
所以在上面的例子中,结果应该是:
userid | recommPoints | likePoints1 | likePoints2
1 | 10 | 1 | 10
2 | NULL | NULL | NULL
3 | 20 | 5 | 4
4 | NULL | NULL | 2