简体   繁体   中英

MySQL - adding join changes count/sum values?

I can't help thinking this is a common question but for the life of me I can't find a solution.

Say I have this query:

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

That works fine. It pulls out users, plus the number of times they've watched any video, plus the number of unique videos they've watched. The values are correct - I've checked.

If I then extend the query with another join, however:

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

...the earlier COUNT / SUM stats are now way off (in this example, total_watches should be 40, and then jumps to 880.)

What am I doing wrong?

I'm pretty sure it's something to do with GROUP BY , and I've tried adding columns to that, but I can't seem to crack this.

Try the following. It uses a subquery computing the count first. The distinct may be unnecessary in this solution as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM