简体   繁体   English

用另一个COUNT表更新一个MySQL表

[英]Updating a MySQL table with the COUNT of another

I'm trying to update a column in table Profiles with a COUNT from another table Videos . 我正在尝试使用另一个表Videos的COUNT更新表Profiles的列。 All videos are stored in the Videos table, and I want to create a column in Profiles called VideoCount which shows the COUNT of that user's videos in the Videos table. 所有视频都存储在Videos表,我想创建一个列Profiles名为VideoCount它显示的是用户对视频的COUNT Videos表。

Basically, I want to run a cron job - so I need to know how to find the COUNT of a user's videos in the Videos table and then UPDATE that user's VideoCount in Profiles with this count number. 基本上,我想执行一项cron作业-因此,我需要知道如何在“ Videos表中找到一个用户的视频的COUNT个,然后使用此计数在“ Profiles更新该用户的VideoCount

To identify who's uploaded which video, Videos . 要确定是谁上传了哪些视频,请Videos Owner and Profiles . OwnerProfiles ID should be made to match. ID应匹配。 Does anybody know the SQL which I need to run for the PHP file cron job? 有人知道我需要为PHP文件cron作业运行的SQL吗?

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

as simple as it can be^^ 尽可能简单^^

and if you want it fancy: all the triggers you might need: 并且如果您想花哨的话:您可能需要所有触发器:

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 ;

If you want to update video count that you can upadate video count at the time of upload, so as i think there is no need for the cron job for this. 如果您要更新视频计数,则可以在上传时更新视频计数,因此,我认为无需为此进行cron工作。

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

Something like 就像是

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
);

I'm not sure this syntax is completely correct. 我不确定此语法是否完全正确。 give it a try 试试看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM