计算总分

Calculate overall score

我有一个包含这些表的数据库

users(name, team_id, overall_user_score)
teams(id, name, team_score, totalscore)

我如何在每次更新后触发 运行,它获取团队中所有用户的分数和该团队的 team_score 并将它们加在一起并放入 totalscore.

我没有任何触发器代码。我有 php 来显示总分,仅此而已。

function showTeamScore() {
    require "connect.php";

    $score = mysqli_query($connection, "SELECT * 
FROM teams 
WHERE id = '".$_GET['id']."'")  or die(mysqli_error($connection));

  while ($data = mysqli_fetch_array($score)) {

 echo $data['overall_score'];
  }

}

编辑:代码和问题更新

mysqli_query($connection, "UPDATE teams SET totalscore=overall_score+IFNULL((SELECT sum(overall_user_score) FROM users WHERE team_id=id),0)") or die(mysqli_error($connection));

一个简单的子查询就可以解决问题:

-- query #1
SELECT id, tname,
   (SELECT sum(uscore) FROM usr WHERE tid=id) tscore
FROM teams ORDER BY id

您可以直接 运行 这个 select 或为其定义一个视图。

如果您只是想要总分,您可以简单地做:

-- query #2
SELECT SUM(uscore) total_score FROM usr

或者,结合之前的团队列表:

-- query #3 (combination of #1 and #2)
SELECT id, tname,(SELECT sum(uscore) FROM usr WHERE tid=id) tscore
FROM teams
UNION ALL
SELECT 999,'total score all teams',SUM(uscore) FROM usr
ORDER BY id

示例数据如 - Demo,请参见此处:http://www.sqlfiddle.com/#!9/9ba5b/4

团队:

id  tname
1   Dallas
2   Houston
3   Austin

用户名:

uid  name   tid  uscore
1    Paul   1     10
2    Mary   1      3
3   Harry   2      7
4   Frank   2      4
5   Lisa    1      15

您将从查询 #3 中得到此结果:

id  tname                 tscore 
1   Dallas                28
2   Houston               11
3   Austin
999 total score all teams 39

好的,如果你想在最后一列中看到所有用户及其各自的团队得分,你可以这样做

-- query #4
SELECT uid, name,uscore,(SELECT sum(uscore) FROM usr WHERE tid=u.tid) tuscore
FROM usr u

这将导致

uid  name uscore  tuscore
1    Paul    10    28
2    Mary     3    28
3    Harry    7    11
4    Frank    4    11
5    Lisa    15    28

全新答案:

您可能需要这样的 update(选择 #4a 或 #4b):

-- query #4a
UPDATE teams t INNER JOIN
(SELECT tid, SUM(uscore) usc FROM usr GROUP BY tid) u ON u.tid=t.id
SET t.tsc=t.tsc+u.usc

或(参见此处http://www.sqlfiddle.com/#!9/040b2/1):

-- query #4b (alternative version)
UPDATE teams SET tsc=tsc+IFNULL((SELECT sum(uscore) FROM usr WHERE tid=id),0)
-- IFNULL avoids the result to become NULL if there are no new contributions

个人用户贡献 uscore 将添加到团队总分 tsc 中。在团队中只有 一个 得分列是有意义的。

与之前的分数

id  tname   tsc
1   Dallas  20
2   Houston  7
3   Austin  18

加上上面列出的用户贡献,新的团队总得分将是

id   tname   tsc
 1   Dallas   48
 2   Houston  18
 3   Austin   18

之后应重置用户分数以避免重复计算。做

UPDATE usr SET uscore=0

(或者你可以在用户 table 中设置一个 "invalidation-flag",如果你仍然希望能够 查看 最后的分数但不计算再次。)