MySQL cell value that depends on other cell values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xQuasar
Forum Newbie
Posts: 19
Joined: Tue Dec 02, 2008 5:53 pm

MySQL cell value that depends on other cell values

Post by xQuasar »

Well, I have a need for one of the cells in mySQL to depend on some other cells.

Say, there's a stat, and it depends on the number of weapons. Uhh, jsut for an example, say attack power = 5000 * no. of swords

Is there any other way to update attack power, APART from getting the number of swords from mysql, multiplying it by 5000 then changing the attack power cell value to that? Because my game is going to have heaps of weapons. and if i'm going to need to do that... >.>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: MySQL cell value that depends on other cell values

Post by requinix »

MySQL doesn't have "formulas" like a spreadsheet program has. You have to do the math yourself, or tell your SELECT or UPDATE query what to calculate each time it runs.

However you can (in recent versions of MySQL) create a "view": it's basically a SELECT query that behaves like a table.

Code: Select all

CREATE TABLE player (id INT AUTO_INCREMENT PRIMARY KEY, swords INT);
INSERT INTO player VALUES (NULL, 5), (NULL, 3), (NULL, 7);
 
CREATE VIEW view_player AS
    SELECT *, swords * 5000 AS attack_power FROM player;
SELECT * FROM view_player;

Code: Select all

+----+--------+--------------+
| id | swords | attack_power |
+----+--------+--------------+
|  1 |      5 |        25000 |
|  2 |      3 |        15000 |
|  3 |      7 |        35000 |
+----+--------+--------------+
Since you're adding information to the view (the attack_power calculation) you can't INSERT data into it.

(Number of swords? You can have more than one or two I guess... I call dibs on General Grevious.)
(I'm joking.)
Post Reply