Mysql计数记录按多个表中的ID分组

时间:2014-09-29 12:12:47

标签: mysql sql

我正在开发一个与facebook集成的应用程序。此应用程序可以作为选项卡应用程序嵌入到FB页面中。

使用页面的FB SDK供稿将存储在供稿表中 页面粉丝可能会喜欢并评论按页面发布的Feed。 用户'喜欢在喜欢表和用户'评论存储在评论

我希望获得每个用户的总计数(喜欢计数+评论数)。

SQL小提琴:http://sqlfiddle.com/#!2/ecb37/10/0

表:供稿

| ID |                         POST_ID |
|----|---------------------------------|
| 56 | 150348635024244_795407097185058 |
| 55 | 150348635024244_795410940518007 |
| 54 | 150348635024244_795414953850939 |
| 53 | 150348635024244_797424133650021 |
| 52 | 150348635024244_797455793646855 |
| 51 | 150348635024244_798997120159389 |
| 50 | 150348635024244_798997946825973 |

表:喜欢

SELECT user_id, COUNT(*) FROM likes GROUP by user_id

|          USER_ID | LIKECOUNT |
|------------------|-----------|
|  913403225356462 |         4 |
|  150348635024244 |         3 |
|  356139014550882 |         2 |
|  753274941400012 |         2 |
| 1559751687580867 |         1 |

表:评论

SELECT user_id, COUNT(*) FROM comments GROUP by user_id

|         USER_ID | COMMENTSCOUNT |
|-----------------|---------------|
| 150348635024244 |             2 |
| 356139014550882 |             2 |
| 913403225356462 |             2 |

结果应该是这样的

| POINTS | LIKESCOUNT | COMMENTSCOUNT |         USER_ID |
|--------|------------|---------------|-----------------|
|      6 |          4 |             2 | 913403225356462 |
|      5 |          3 |             2 | 150348635024244 |
|      4 |          2 |             2 | 356139014550882 |
|      2 |          2 |             0 | 753274941400012 |
|      1 |          1 |             0 |1559751687580867 |

我尝试了这个查询。但是每个用户的数量都是错误的

SELECT COUNT(likes.user_id)+COUNT(comments.user_id) as points, likes.user_id FROM `likes` 
LEFT JOIN comments ON likes.user_id = comments.user_id 
LEFT JOIN feeds ON likes.post_id = feeds.post_id 
WHERE likes.post_id LIKE '153548635024244%' 
GROUP BY likes.user_id 
ORDER BY points DESC

2 个答案:

答案 0 :(得分:1)

两个查询无关,连接无用。使用UNION ALL:

SELECT user_id, sum(n) from (
    SELECT user_id, COUNT(*) n FROM likes GROUP by user_id
    UNION ALL
    SELECT user_id, COUNT(*) FROM comments GROUP by user_id
) x
GROUP BY user_id

需要UNION ALL而不仅仅是UNION,因为UNION会删除重复项,并且会导致两个子查询的边缘情况产生不正确的结果,从而产生相同的计数。

答案 1 :(得分:0)

获得所需内容的简单方法是使用count(distinct)。但这可能会有糟糕的表现。相反,使用相关子查询:

SELECT COUNT(*) +
       (select COUNT(c.user_id) from comments c where c.user_id = l.user_id)
       ) as points, l.user_id
FROM likes l
WHERE l.post_id LIKE '153548635024244%' 
GROUP BY l.user_id 
ORDER BY points DESC;

我不确定feeds表的用途。但是,您的查询版本会在不同的表之间创建笛卡尔积。如果您对给定用户有很多活动,那对性能来说非常糟糕。