I store some kind of user actions X in my database. If an user does another action Y, the field 'New_actions' is count by 1. So for example:
User does action X at 19:07
User does action Y at 19:08
User does action Y at 19:08
User does action X at 19:10
User does action Y at 19:12
Now I have the next 开发者_JS百科values in my database:
X_actions --- Time --- New_actions
Name1 - 19:07 - 3
Name2 - 19:10 - 1
That means that action Y was done two times after Name1 and one time after Name2. I hope you understand me. But I have a question about that. Every hour 2 actions should be removed. The first time it shouldn't be a problem: The 'New_actions' field in Name1 should be edited to 1, but how can I make a script that the second time Name1 should be edited to 0, and Name2 also?
SET @remove := 2;
UPDATE my_table
SET New_actions =
IF( New_actions >= @remove,
(@remove := 0) + New_actions - @remove,
IF(@remove := @remove - New_actions, 0, 0) )
WHERE New_actions <> 0
ORDER BY my_table.Time;
Used an INT Time column to simplify things, here is the result of executing above block three times:
+------+-------------+
| Time | New_actions |
+------+-------------+
| 1 | 3 |
| 2 | 3 |
| 3 | 3 |
+------+-------------+
+------+-------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 3 |
+------+-------------+
+------+-------------+
| 1 | 0 |
| 2 | 2 |
| 3 | 3 |
+------+-------------+
+------+-------------+
| 1 | 0 |
| 2 | 0 |
| 3 | 3 |
+------+-------------+
It seems you want to do stored procedure :)
http://dev.mysql.com/doc/refman/5.0/fr/stored-procedures.html
精彩评论