我有一个包含这些表的数据库
users(name, team_id, overall_user_score)
teams(id, name, team_score, totalscore)
如何在每次更新后生成一个触发器,在该更新中,它会获取团队中所有用户的分数以及该团队的team_score
并将它们添加到一起并将其放入totalscore
。< / p>
我没有任何触发器代码。我有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));
答案 0 :(得分:1)
一个简单的子查询可能会起到作用:
-- query #1
SELECT id, tname,
(SELECT sum(uscore) FROM usr WHERE tid=id) tscore
FROM teams ORDER BY id
您可以直接运行此选择,也可以为其定义视图。
如果只是想要总分,您可以这样做:
-- 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
使用样本数据,例如 - 演示,请参阅此处:http://www.sqlfiddle.com/#!9/9ba5b/4
队:
id tname
1 Dallas
2 Houston
3 Austin
USR:
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
(或者,您可以在用户表格中设置“invalidation-flag”,如果您仍希望能够查看最后得分但不再计算。)