简体   繁体   中英

How do I make a field in MySQL automatically update depending on another field?

I'm creating a PHP/MySQL Star Wars browser game for fun. I have an experience (xp) field. I also have a rank field. I want it so that - Depending on the amount of XP in the experience field, the rank field would also change. So, if I have 0 to 300 xp, the rank field would be Jedi Initiate. If I have 300 to 700 xp, the rank field would be Padawan. If I have 700 to 1000, the rank field would be Jedi Knight. I want it to automatically update. Is this possible?

I advise a different approach.

Create a second table where you manage the ranks, something like this:

id |    xp  | rank
---+--------+--------------
 1 |      0 | Initiate 
 2 |    300 | Padawan
 3 |    700 | Jedi Knight

Then you can reference in SQL queries where you need the rank on the xp, something like this:

SELECT P.*, R.*
FROM players P 
LEFT JOIN ranks R ON P.`player_xp` <= R.`xp` 
GROUP BY P.`player_xp`;

This is just a rough example on how this can be solved, maybe it needs some fine adjustments. But with this approach you'll have more control over titles. As a sideeffect you'll avoid having alot of duplicate data in the tables, too.

No, a trigger is a bad choice.

It would be something like

CREATE TRIGGER updateRank AFTER UPDATE ON yourTable...

So it would run everytime you update your table, regardless if you update the xp of your player or anything else.

Write a stored procedure with which you update your player's xp and at the same time check if the rank is still correct or needs to get updated to.

Or maybe you don't even need a stored procedure. This is not tested but this could work also:

   UPDATE yourTable SET 
   xp = $theXPthePlayerEarnedWhilePlaying,
   rank = 
   CASE WHEN $theXPthePlayerEarnedWhilePlaying BETWEEN 0 AND 299 THEN 'Jedi Initiate'
   WHEN $theXPthePlayerEarnedWhilePlaying BETWEEN 300 AND 699 THEN 'Padawan'
   /*...*/
   ELSE 'unranked Player'
   END 
   WHERE playerId = $yourPlayer;

EDIT: This is a pretty good tutorial to stored procedures if you want to know more. Don't get scared, it's not that much and not too hard to figure out. http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx

No! MySQL can't do it for you. But you can tell MySQL one time, and it takes care of it from there.

I am talking about the triggers. You need to create a trigger (unless you want to handle it in your php code) what mysql should do when the experience changes

Read about creating triggers in the manuals

尝试使用触发器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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