使用另一个的COUNT更新MySQL表

时间:2010-11-30 14:46:24

标签: php mysql cron

我正在尝试使用另一个表Profiles中的COUNT更新表Videos中的列。所有视频都存储在Videos表中,我想在Profiles中创建一个名为VideoCount的列,该列显示Videos表中该用户视频的COUNT。 / p>

基本上,我想运行一个cron作业 - 所以我需要知道如何在Videos表中查找用户视频的COUNT,然后在VideoCount中更新该用户的Profiles这个计数。

要确定哪些人上传了哪个视频,VideosOwnerProfilesID应该匹配。有没有人知道我需要为PHP文件cron作业运行的SQL?

3 个答案:

答案 0 :(得分:3)

UPDATE Profiles
SET VideoCount = (
   SELECT COUNT(*)
   FROM Videos
   WHERE Videos.Owner = Profiles.ID);

尽可能简单^^

如果你想要它的幻想:你可能需要的所有触发器:

DELIMITER //

CREATE TRIGGER increaseVideoCount AFTER INSERT ON Videos
  FOR EACH ROW BEGIN
    UPDATE Profiles SET VideoCount = VideoCount + 1 WHERE ID = NEW.Owner;
  END;
//

CREATE TRIGGER decreaseVideoCount AFTER DELETE ON Videos
  FOR EACH ROW BEGIN
    UPDATE Profiles SET VideoCount = VideoCount - 1 WHERE ID = OLD.Owner;
  END;
//

CREATE TRIGGER checkVideoCount AFTER UPDATE ON Videos
  FOR EACH ROW BEGIN
    IF OLD.Owner <> NEW.Owner THEN
      UPDATE Profiles SET VideoCount = VideoCount + 1 WHERE ID = NEW.Owner;
      UPDATE Profiles SET VideoCount = VideoCount - 1 WHERE ID = OLD.Owner;
    END IF;
  END;
//

DELIMITER ;

答案 1 :(得分:2)

如果您想更新视频计数,您可以在上传时更新视频计数,因此我认为不需要cron作业。

update profiles set videocount=(select count(*) from videos where profileid =$profileid ) 
where profileid=$profileid

答案 2 :(得分:1)

这样的东西
UPDATE A SET VideoCount = 
(
  SELECT COUNT(B.*) 
  FROM Videos AS B INNER JOIN Profiles AS B ON (A.Profile_ID = B.Owner_ID)  
  GROUP BY B.Owner_ID
);

我不确定这种语法是否完全正确。试一试