简体   繁体   English

在SQL查询中生成总计列,联接多个表

[英]Generating total column in SQL query, joining multiple tables

I have a league system with teams, users, and then points transactions. 我有一个包含团队,用户和积分交易的联赛系统。

Each row in the points table links to a user's ID, each user row links to a team ID. 积分表中的每一行都链接到一个用户的ID,每个用户行都链接到一个团队的ID。

When I pull the teams from the database I want to also return a column that has the total points for that team by summing all the points associated with users in that team. 当我从数据库中提取团队时,我还想通过汇总与该团队中与用户相关的所有积分,返回一列包含该团队总积分的列。 I have the following code that returns the correct points total independently: 我有以下代码可单独返回正确的总点数:

SELECT SUM(ar_points.amount) AS total_points FROM ar_teams, ar_users, ar_points WHERE ar_teams.id = ar_users.team_id AND ar_users.id = ar_points.user_id AND ar_teams.id = :id

When I pull the normal team information, it pushes the results into an object for each team: 当我提取正常的团队信息时,它将结果推入每个团队的对象中:

$sql = $db->query("SELECT * FROM ar_teams");
$sql->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,'Team');
$sql->execute();
return $sql->fetchAll();

I want to combine these two queries so that the total points value gets put into the object as another property. 我想结合这两个查询,以便将总点值作为另一个属性放入对象。

SELECT   ar_teams.*, SUM(ar_points.amount) AS total_points
FROM     ar_teams
    JOIN ar_users  ON ar_users.team_id  = ar_teams.id
    JOIN ar_points ON ar_points.user_id = ar_users.id
GROUP BY ar_teams.id

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

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