简体   繁体   中英

MySQL Update or Insert an integer value with multiple queries to change it at same time

I have an integer column in a MySQL table that I want to add one to or subtract one from (call it a point system).

AFAIK the two options to this are updating the int column of a single row in a table or inserting a new row every time there is a change as shown below.

id | int
1  | 5
2  | 4
3  | 5
4  | 6

I'm not sure which to choose, since it is possible that many users may be sending queries to change this number, so I don't want the queries to be adding or subtracting a historical number.

Which is the better way or is there a way that is even better that I have not yet considered? (By 'better' I mean less likely to fail under pressure from lots of queries trying to add/subtract the value). I've heard about locking and transactions, but not sure how to implement them in this simple system that I'm sure lots of applications with this problem have solved.

Thanks.

This is more of a comment than an answer.

You don't provide enough information to really answer the question. The key is how the results are going to be used.

Inserting a record into a table is usually faster than updating one, because the SQL engine doesn't need to search for the record in the first place. Of course, this gets more complicated if you have indexes and unique constraints on the table.

On the other hand, if you need to know the total value, then adding up the values in the table takes time.

So, the balance is really between how often you have increments versus how often you look at the sums. If you never look at the sums, the insert is probably faster. In general, though, I would lean toward updating the values.

I would figure that updating the integer value for the id would be the correct way to handle this. As there is obviously the potential for multiple requests to update the integer value at the same time you don't want to use a set in stone query like this:

UPDATE pointstable SET int = 7 WHERE id = '4';

Instead you want the query to perform the math increment like this:

UPDATE pointstable SET int = (int + 1) WHERE id = '4';

for a simple case you can make use of MySQL MyISAM engine and use table locking for concurrency - the locking is very quick. Unless you are talking like a million people trying to update the counter, scalability should not be an issue

so the algorithm is

when a user wishes to modify the number you do this

LOCK TABLES pointstable WRITE; 
UPDATE pointstable SET int = (int + 4) WHERE id = 3;
UNLOCK TABLES; 

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