-2

这个查询

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
4

1 回答 1

2

基本问题是每个连接都会为连接值添加多行。因此,您最终会多次计算事物。解决它的一般方法是使每个单独的分组单独的子选择。您可以将一个作为主要选择的一部分。

诊断这类问题的一个好方法是删除 group by,然后查看底层数据集。使用 where 子句来限制已知的不起作用的情况。

Select
    u.username, 
    p1.likePoints1, 
    p1.recommPoints,
    Sum(p2.likes) * 2 As likePoints2 -- assume the *2 is part of the algorithm
From
    users u
        Left Outer Join (
            Select
                r.recommendedByUserId rid,
                Sum(p.likes) AS likePoints1,
                Count(Distinct r.id) * 10 As recommPoints
            From
                users r
                    Left Outer Join
                posts p
                    On r.id = p.author_id And 
                       p.created >= Date('2013-09-16') And
                       p.created <= Date('2013-09-30')
            Where
                r.created >= Date('2013-09-16') And 
                r.created <= Date('2013-09-30')
            Group By
                r.recommendedByUserId
    ) p1
        on u.id = p1.rid
        Left Outer Join
    posts p2
        On p2.author_id = u.id And
           p2.created >= Date('2013-09-16') And
           p2.created <= Date('2013-09-30')
Group By
    u.username,
    p1.likePoints1,
    p1.recommPoints

削减Example Fiddle

于 2013-09-21T22:58:46.140 回答