简体   繁体   English

连接3个表时SQL使用计数和总和

[英]SQL Using count and sum when joining 3 tables

When I try to join 2 tables and use SUM or COUNT it all works perfectly and as expected. 当我尝试加入2个表并使用SUM或COUNT时,它们都可以正常工作并且符合预期。 However when I join 3 tables SUM and COUNT makes no sense because the JOIN statements create extra rows for each table to have a unique row so they over count and over sum the required values. 但是,当我连接3个表时,SUM和COUNT没有意义,因为JOIN语句为每个表创建了额外的行以具有唯一的行,因此它们过多地计数了所需的值。

Here is the query: 这是查询:

SELECT PO_club.clubid, PO_club.name, PO_club.pic, PO_club.points, count(PO_club_user.userid), SUM(PO_club_point_log.points)
FROM PO_club 
INNER JOIN PO_club_user ON PO_club.clubid = PO_club_user.clubid 
LEFT JOIN PO_club_point_log ON PO_club.clubid = PO_club_point_log.clubid 
WHERE PO_club.deleted = 0 
GROUP BY PO_club.clubid 
ORDER BY PO_club.points DESC;  

If I run two separate scripts like first join only PO_club and PO_club_user to get COUNT() it works. 如果我像先运行两个单独的脚本那样只加入PO_club and PO_club_user来获得COUNT()它将起作用。 And then run PO_club JOIN PO_club_point_log to get SUM() its all good. 然后run PO_club JOIN PO_club_point_log以获得SUM()的所有好处。 However, I need to run it one script so that i would not need to sort it at the front end. 但是,我需要运行一个脚本,这样我就无需在前端对其进行排序。 Is there a way to join 3 tables and somehow COUNT() just work on PO_club and PO_club_users while SUM only on PO_club and PO_club_point_log ? 有没有一种方法可以PO_club and PO_club_users join 3 tables并且以某种方式COUNT()仅对PO_club and PO_club_usersSUM仅对PO_club and PO_club_point_log

Thanks! 谢谢!

How's this? 这个怎么样? This will include all PO_clubs even if they don't have any users in case they have points. 这将包括所有PO_club,即使没有积分的情况下也没有用户。 If that's not what you want, change the first LEFT JOIN to INNER JOIN . 如果这不是您想要的,请将第一个LEFT JOIN更改为INNER JOIN

SELECT PO_club.clubid, PO_club.name, PO_club.pic, PO_club.points, count(PO_club_user.userid), t.sum_points
FROM PO_club
LEFT JOIN PO_club_user ON PO_club.clubid = PO_club_user.clubid
LEFT JOIN
(SELECT PO_club_point_log.clubid, SUM(PO_club_point_log.points) AS sum_points
FROM PO_club_point_log INNER JOIN PO_club ON PO_club_point_log.clubid = PO_club.clubid
GROUP BY PO_club_point_log.clubid) AS t
ON PO_club.clubid = t.clubid
WHERE PO_club.deleted = 0
GROUP BY PO_club.clubid
ORDER BY PO_club.points DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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