How to increment in SQL using a trigger?

匿名 (未验证) 提交于 2019-12-03 02:35:01

问题:

So I have a table that holds a list of cuisines and a total of how many restaurants there are with that cuisine. (e.g. Italian | 7)

I'm trying to set-up a trigger in phpMyAdmin that will increment the total every time a new restaurant is added to the database. Here is what I have so far:

CREATE TRIGGER UpdateStats AFTER INSERT ON Restaurant BEGIN     UPDATE RestaurantStats SET TotalRestaurants = TotalRestaurants + 1 WHERE Cusine = NEW.cusine; END; 

But I keep getting an error message and it's telling me that it has to do with my Syntax. Where am I going wrong? I followed the example I saw pretty well.

Here is the error message:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BEGIN UPDATE RestaurantStats SET TotalRestaurants = TotalRestaurants + 1 WHERE' at line 2 

回答1:

do you have to have for each row

CREATE TRIGGER UpdateStats  AFTER INSERT ON Restaurant  FOR EACH ROW      UPDATE RestaurantStats SET TotalRestaurants = TotalRestaurants + 1 WHERE Cusine = NEW.cusine; 


回答2:

You need to use FOR EACH ROW and get rid of the BEGIN...END like this:

CREATE TRIGGER UpdateStats AFTER INSERT ON Restaurant FOR EACH ROW     UPDATE RestaurantStats SET TotalRestaurants = TotalRestaurants + 1 WHERE Cusine = NEW.cusine; 

BEGIN...END is only used for multiple queries in the same trigger and requires redefinition of the termination character. So your first ; is terminating the statement and leaving the BEGIN open without an END.



回答3:

try with "for each row":

CREATE TRIGGER UpdateStats AFTER INSERT ON Restaurant FOR EACH ROW BEGIN     UPDATE RestaurantStats SET TotalRestaurants = TotalRestaurants + 1 WHERE Cusine = NEW.cusine; END; 

Haven't tried it myself so not sure if it works...



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