MySQL Trigger to update count after insert

ぃ、小莉子 提交于 2020-01-03 03:12:06

问题


I need some help with a mysql trigger. I am currently trying to tidy up some code and offload some processing to the mysql database rather than running 2 queries and joins etc...

When someone inserts into a video into a database, I would like the video count in the category to update.

So you specify the category id.

This is what I have so far so any help would be good as i just dont seem to be able to get the syntax correct.

CREATE TRIGGER 'db_videos'.'update_video_count'
AFTER INSERT ON 'videos' FOR EACH ROW
BEGIN
    UPDATE video_cat WHERE video_count = video_count + 1 WHERE video_cat = video_cat;
END;

回答1:


Your where clause is duplicated and ambiguous. If I understand your data model correct, try:

CREATE TRIGGER 'db_videos'.'update_video_count'
AFTER INSERT ON 'videos' FOR EACH ROW
BEGIN
    UPDATE video_cat vc 
      WHERE video_count = video_count + 1 
      and NEW.video_cat = vc.video_cat;
END;



回答2:


try the following:

CREATE TRIGGER 'db_videos'.'update_video_count'
AFTER INSERT ON 'videos' FOR EACH ROW
BEGIN
    UPDATE video_cat vc 
      SET video_count = video_count + 1 
      WHERE NEW.video_cat = vc.video_cat;
END;


来源:https://stackoverflow.com/questions/10113808/mysql-trigger-to-update-count-after-insert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!