简体   繁体   中英

MySql count of rows and insert into the table that count

I have a scenario where i need to take count of rows in mysql table for the current branch(in that table we are store branch) and insert the count of rows with other details into the same table. But the problem is when two or more concurrent users try to insert from the same branch at the same time the count is same for all the users, but for me the insert should not happ for the other user(s) until i read the count and insert that one user request . Is there any way the locking works for this and any example would be helpful(All i need to do this in MySql store procedure)

Edit : Sorry, I cant share the working code but i can write example here

My table structure is here

id    name    branchid    count
1     abc     1           1
2     xyz     1           2
3     abcd    2           1
4     wxyz    2           2

Here am taking count of rows from the above table for given branch(ex : 1) and inserting the row with that calculated count

Ex :

set @count = (select count(id) from tbl where branchid = 1);

later

insert into tbl(id, name, branchid, count)
values(5, 'abcd', 1, @count)

This works great provided if only one user access this from one branch , but if more than one user from same branch try to access this at exact same time the

@count 

is duplicating for the branch users.

Why not just do it in one query:

insert into tbl(id, name, branchid, count)
select 5, 'abcd', 1, count(*)
from from tbl 
where branchid = 1;

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