我有几个表,每个表都有自己的每个用户的分数。我想创建一个触发器,它将为每个用户添加所有这些分数,并将它们放在users表中名为score的字段中。
WebElement
//整体_score已经有了一个值,所以我只想将其他表中的得分字段添加到这个。
答案 0 :(得分:0)
要从多个表中选择数据,您可以使用SQL JOINS。
请参阅以下示例:
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
此代码将从table1,table2和table3中选择得分列,并为每个user_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
答案 1 :(得分:0)
要实现这一点,首先要编写选择查询,并从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
以下是演示http://www.sqlfiddle.com/#!9/6f936/1
现在让我们将select转换为更新命令,它将为
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)