I'm making a small game and I need to have a trigger on my members
table, which will check the experience
column, and anytime it gets bigger than certain values, the level
will become level+1
. This is the trigger:
DELIMITER $$
CREATE TRIGGER update_level AFTER UPDATE ON members
FOR EACH ROW BEGIN
IF experience < 1000 THEN
SET members.level = 1
ELSE IF experience < 2400 THEN
SET level = 2
ELSE IF (experience < 4000) THEN
SET level=3
ELSE IF (experience < 8000) THEN
SET level=4
ELSE IF (experience < 15000) THEN
SET level=5
ELSE IF (experience < 24000) THEN
SET level=6
ELSE IF (experience < 35000) THEN
SET level=7
ELSE IF (experience < 50000) THEN
SET level=8
END IF
END
$$
DELIMITER ;
phpMyAdmin always responds with this error code:
#1064 – You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
I spent about 2 hours trying to figure it out, but it looks like I can't do it by myself. What I have tried is to change the IF
statement to a CASE
statement (simple switch). I have tried it with WHEN xxx THEN SET
. Also with UPDATE
. Another thing I have tried was to add ' ' and " " everywhere around the column names and values – didn't help at all.
Can you please advise me about what's the best way to accomplish this? I'm pretty sure there is some small mistake there, and if not that, then my approach must be wrong.
Best Answer
When trying to compile the original trigger code, we encounter quite a few issues. As some colleagues have pointed out, the timing ("after") should be adjusted. There are some syntactical and logical problems, too (eg < instead of >). Maybe it would be better to use BETWEEN ... AND ... for defining the "levels".
Trigger (MySQL 5.7)
Testing
ALTERNATIVE
A VIEW may be a better solution for this scenario. We could use a different table layout for MEMBERS, and avoid storing levels ("level" depends on "experience", not on member_id ...), like so (MariaDB 10.2):
Now we can find the current level associated with a member_id by SELECTing from the VIEW. No trigger required.
Testing
See dbfiddle here.
Another alternative (MariaDB version 5.2+, MySQL 5.7)
Use a virtual column, let the DDL do the work.
Dbfiddle here.