根据其他人的总和更新表中的字段

时间:2015-05-27 10:03:02

标签: mysql mysqli phpmyadmin

我有两张桌子:

用户:{id,name,studentid,overall_score} userbadges:{id,badge_id,user_id,level,score}

用户可以拥有多个徽章。

我希望将overall_score更新本身作为userbadges中所有分数的总和,其中user_id匹配用户表中的id。

这可以作为触发器完成吗?

我有一个mysql语句在php中工作,它只显示总分,但实际上并没有更新任何内容。

PHP:

$userscore = mysqli_query($connection,"

SELECT users.studentid
     , SUM(score) AS TotalItemsOrdered
  FROM userbadges ub
 INNER 
  JOIN users 
    ON users.id = ub.user_id
  WHERE studentid = $_SESSION['studentid']
")  or die(mysqli_error($connection));


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

echo $data['TotalItemsOrdered']; 

2 个答案:

答案 0 :(得分:2)

尝试此查询(已编辑):

 update USERS u 
 set u.overall_score = 
 ( select sum(b.score) from USERBADGES b 
   where b.user_id=u.id  ) ;

现在如果您想每天自动运行此查询,请使用MySQL调度程序,如下所示:

 DELIMITER $$
 CREATE EVENT update_users_table
 ON SCHEDULE EVERY 1 DAY
 STARTS '2015-05-27 00:00:00'
 DO 
 BEGIN
    update USERS u 
    set u.overall_score = 
    ( select sum(b.score) from USERBADGES b 
     where b.user_id=u.id  ) ;
 END$$    
 DELIMITER ;

如果您想在更新后自动运行此查询,请转到触发器:

 DELIMITER $$
 CREATE TRIGGER update_users_trigger AFTER UPDATE ON USERBADGES
 FOR EACH ROW
 BEGIN
    IF NEW.score <> OLD.score THEN  
        update USERS u 
        set u.overall_score = 
       ( select sum(b.score) from USERBADGES b 
         where b.user_id=u.id  ) ;
    END IF;
 END$$
 DELIMITER ;

答案 1 :(得分:0)

Sagar的触发器是一种解决方案。但是,这个版本效率更高:

 DELIMITER $$
 CREATE TRIGGER update_users_trigger AFTER UPDATE ON USERBADGES
 FOR EACH ROW
 BEGIN
    IF NEW.score <> OLD.score THEN  
        update USERS u 
            set u.overall_score = u.overall_score  + new.score - old.score                          
            where u.user_id = new.user_id;
    END IF;
 END$$

或者,如果您希望完全重新计算:

 DELIMITER $$
 CREATE TRIGGER update_users_trigger AFTER UPDATE ON USERBADGES
 FOR EACH ROW
 BEGIN
    IF NEW.score <> OLD.score THEN  
        update USERS u 
            set u.overall_score = (select sum(b.score)
                                   from USERBADGES b 
                                   where b.user_id = u.id
                                  )
            where u.user_id = new.user_id
------------^
    END IF;
 END$$
 DELIMITER ;

为了提高性能,您需要userbadges(user_id, score)上的索引。