获得每个用户的所有帖子的总投票数

时间:2017-05-03 07:52:31

标签: mysql sql laravel

数据库结构如下:

用户

[id] [name]    [etc...]
1    Echolot   ...
2    AnotherUser  ...

帖子

[id] [user_id] [title] [etc...]
1    1         Post1   ...
2    1         Post2   ...

posts_upvotes

[id] [post_id] [user_id (user who voted)] [value (1 or 0 or -1)]
1    1         1                          1
2    1         2                          -1
3    2         1                          1
4    2         2                          1

我试图获取所有用户及其所有帖子收集的所有用户总数sum(value)的列表,如下所示:

id: 1
name: Echolot
upvoteCount: 2

id: 2
name: AnotherUser
upvoteCount: 0

我尝试使用以下查询但没有成功,我得到错误的值而不是正确数量的结果:

          SELECT joinedUsers.id, joinedPosts.postCount, joinedPostsUpvotes.upvoteCount
          FROM users joinedUsers
          inner join (
            SELECT user_id, id, count(id) as postCount
            FROM posts
            GROUP BY user_id, id
          ) joinedPosts on joinedPosts.user_id = joinedUsers.id
          inner join (
            SELECT post_id, sum(value) as upvoteCount
            FROM posts_upvotes
            GROUP BY post_id
          ) joinedPostsUpvotes on joinedPostsUpvotes.post_id = joinedPosts.id
          GROUP BY joinedUsers.id, joinedPosts.postCount, joinedPostsUpvotes.upvoteCount

提前感谢您提供任何提示或解决方案。

编辑:添加了测试数据和预期结果。

3 个答案:

答案 0 :(得分:2)

您不需要所有这些子查询,您可以在left joinuserpost之间使用一对post_upvotes

SELECT  t1.id, t1.name, count(distinct t2.id), sum(t3.value)
FROM    users t1
LEFT JOIN
        posts t2
ON      t1.id = t2.user_id
LEFT JOIN    
        posts_upvotes t3
ON      t2.id = t3.post_id
GROUP BY t1.id, t1.name

使用left join代替inner join可确保您不会显示没有帖子或没有投票的帖子的用户。

答案 1 :(得分:1)

如果你想要某人投票的次数(未经测试),我认为会是这样的。

SELECT users.id, users.name, COUNT(posts_upvotes.id) as upvoteCount
      FROM users
      INNER JOIN posts_upvotes ON posts_upvotes.user_id = users.id
      GROUP BY users.id

或者如果你想要upvotes的值的总和:

SELECT users.id, users.name, SUM(posts_upvotes.id) as upvoteSum
      FROM users
      INNER JOIN posts_upvotes ON posts_upvotes.user_id = users.id
      GROUP BY users.id

或者在Laravel中,您可以使用查询构建器:https://laravel.com/docs/5.4/queries

这样的事情:

DB::table('users')
    ->join('posts_upvotes', 'users.id', '=', 'posts_upvotes.user_id'))
    ->groupBy('users.id')
    ->select('users.id', 'users.name', DB::raw('COUNT(posts_upvotes) as upvoteCount'))
    ->get();

答案 2 :(得分:1)

我认为这可以帮到你:

SELECT u.id,
  u.name,
  COUNT(p.id)
  SUM(pu.value)
FROM users AS u
JOIN posts AS p
ON u.id = p.user_id
JOIN posts_upvotes AS pu
ON p.id = pu.post_id
GROUP BY u.id,
  u.name

如果我没有遗漏你的问题。