MySQL - 添加连接更改计数/总和值?

时间:2018-01-11 13:12:24

标签: mysql sql count aggregate-functions

我不禁想到这是一个常见的问题,但对于我的生活,我找不到解决方案。

说我有这个问题:

SELECT
    ue.user,
    SUM(w.times) AS total_watches,
    COUNT(w.vid_id) AS total_unique_watches,
FROM users ue
LEFT JOIN watches w ON w.user_id = ue.user
WHERE ue.user = "fv9jgpd1cmo" && ue.user_type IN ("ds", "s")
GROUP BY ue.user

工作正常。它会拉出用户,加上他们观看任何视频的次数,以及他们观看过的独特视频数量。价值是正确的 - 我已经检查过了。

如果我然后用另一个连接扩展查询,那么:

SELECT
    ue.user,
    SUM(w.times) AS total_watches,
    COUNT(w.vid_id) AS total_unique_watches,
    COUNT(DISTINCT m.linked_vid_evt) AS answered_vid_events
FROM users ue
LEFT JOIN watches w ON w.user_id = ue.user
LEFT JOIN messages m ON m.from_uid = ue.user /* <-- new join */
WHERE ue.user = "fv9jgpd1cmo" && ue.user_type IN ("ds", "s")
GROUP BY ue.user

...之前的COUNT / SUM统计信息现已关闭(在此示例中,total_watches应为40,然后跳转到880.)

我做错了什么?

我很确定它与GROUP BY有关,我已经尝试过添加列,但我似乎无法解决这个问题。

1 个答案:

答案 0 :(得分:1)

尝试以下方法。它使用子查询首先计算count。此解决方案中也可能不需要distinct

SELECT
    ue.user,
    SUM(w.times) AS total_watches,
    COUNT(w.vid_id) AS total_unique_watches,
    m.answered_vid_events
FROM users ue
LEFT JOIN watches w ON w.user_id = ue.user
LEFT JOIN (
   SELECT from_uid, COUNT(DISTINCT linked_vid_evt) answered_vid_events
   FROM messages
   GROUP BY from_uid 
) m ON m.from_uid = ue.user
WHERE ue.user = "fv9jgpd1cmo" && ue.user_type IN ("ds", "s")
GROUP BY ue.user