Php 从其他表更新用户分数
我有几个表,每个表都有各自用户的分数。我想创建一个触发器,将每个用户的所有分数相加,并将它们放在users表中名为score的字段中Php 从其他表更新用户分数,php,mysql,Php,Mysql,我有几个表,每个表都有各自用户的分数。我想创建一个触发器,将每个用户的所有分数相加,并将它们放在users表中名为score的字段中 Tables (They essentially have the same fields with a few different ones) : Table 1 : {id, user_id, score} Table 2 : {id, user_id, score} Table 3 : {id, user_id, score} users : {id,
Tables (They essentially have the same fields with a few different ones) :
Table 1 : {id, user_id, score}
Table 2 : {id, user_id, score}
Table 3 : {id, user_id, score}
users : {id, name, overall_score}
//总分已经有了一个值,所以我只想将其他表中的分数字段添加到此表中。要从多个表中选择数据,可以使用 请参见下面的示例:
SELECT table1.score, table2.score, table3.score
FROM table1 LEFT JOIN table2
ON table1.id=table2.id LEFT JOIN table3 ON table1.id=table3.id
此代码将从表1、表2和表3中选择分数列,并为每个用户id创建一行,每行包含一个分数列/表(在本例中为3/行)。这几乎就像有第四个包含所有分数的表,然后在PHP中获取它们时,就像从数据库中获取现有行
编辑:
要在同一查询中更新users表,可以使用以下方法:
UPDATE `users`,
(
SELECT table1.id as tid, table1.score as t1,
table2.score as t2, table3.score as t3
FROM table1 LEFT JOIN table2 ON table1.id=table2.id
LEFT JOIN table3 ON table1.id=table3.id
) as total
SET total_score = (t1 + t2 + t3) WHERE id = tid
为了实现这一点,让我们首先编写select查询,并从3个给定的表中获取每个用户的所有分数之和,这就是如何实现的
select u.*, y.total from users u
left join
(
select user_id,sum(score) as total from(
select user_id, score from table_1
union all
select user_id, score from table_2
union all
select user_id, score from table_3
)x group by x.user_id
)y on y.user_id = u.id
这是演示
现在,让我们将select转换为update命令,如下所示
update users u
left join
(
select user_id,sum(score) as total from(
select user_id, score from table_1
union all
select user_id, score from table_2
union all
select user_id, score from table_3
)x group by x.user_id
)y on y.user_id = u.id
set u.overall_score = coalesce(y.total,0)
这是演示您有多少个具有相同数据结构的表,如您提到的3所列,那么从所有表到用户表的总分是多少?呃,如果iv理解正确,是的。表1-3对每个用户都有自己的分数。我想把它们加起来,(比如在更新之后)并将它们添加到总的_分数有没有一种方法可以用这个来实际更新用户表中的总的_分数?