mysql-添加连接更改count/sum值?

nwsw7zdq  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(277)

我忍不住想这是一个常见的问题,但就我的一生而言,我找不到解决办法。
假设我有这个问题:

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 ,我尝试过在上面添加列,但似乎无法破解。

g6ll5ycj

g6ll5ycj1#

请尝试以下操作。它使用子查询计算 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

相关问题