I wanted to create a system to track the progress of a player in a game. Each player can be a member of multiple groups, which all have other requirements. In order to track his progress, the stats of the player will be saved once he joins a group. Every time he reloads his stats, the current ones should be saved inside the database.

All stats of the player are stored in a json-format, which will then be parsed either by PHP or JS. An entry with compare = 0 is set once the player joins a group. An entry with compare = 1 should be created the first time a player clicks on Update Stats and from then on it should only be updated, not newly created.

Now my question is: How to achieve that? When reading through the syntax of INSERT INTO I got the following:

INSERT INTO `groups` (`grp`, `id`, `json`, `compare`) VALUES 
($grp, $id, $json, 1) ON DUPLICATE KEY SET `json` = $json

However, since there is no key set, and I don't know if I can set up two/three keys (as there can be multiple groups per user, as well as the compare = 0 entry in the same group), I don't think I can do it this way.

+------+----+---------+---------+
| grp  | id | json    | compare |
+------+----+---------+---------+
|  1   |  1 |  stats  |    0    |
|  1   |  1 |  stats  |    1    |
|  1   |  2 |  stats  |    0    |
|  1   |  2 |  stats  |    1    |
|  2   |  2 |  stats  |    0    |
|  2   |  3 |  stats  |    0    |
|  2   |  3 |  stats  |    1    |
|  2   |  4 |  stats  |    0    |
|  2   |  5 |  stats  |    0    |
+------+----+---------+---------+

grp is the group of the player. There is no real limit set to the number of groups a player can be in.

id is the ID of the player.

json contains the stats of the player in a json format (number of points, etc).

compare is a boolean. 0 stands for entry stats (the number of points a player already had when he registered) and 1 stands for the current stats - Which will be compared to the entry stats, in order to get the difference (= the points a player made since joining the group).

I hope my explanation was understandable and someone can help me out.

有帮助吗?

解决方案 2

You can create a unique key with multiple columns. This will trigger the 'on duplicate' clause.

ALTER TABLE groups
ADD UNIQUE (grp, id, compare)

其他提示

You can use insert raplace:

REPLACE INTO groups (`grp`, `id`, `json`, `compare`) VALUES (...);

But you must have primary key in table. Replace into automaticly finds out primary key and if record exists, it update row, but if doesn't, it add new row.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top