简体   繁体   English

MySQL的行计数并插入到该表中

[英]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. 我有一种情况,我需要获取mysql表中当前分支的行数(在该表中,我们是store分支),并将具有其他详细信息的行数插入到同一表中。 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) 有什么方法可以对此进行锁定,任何示例都将有所帮助(我需要在MySql存储过程中完成所有操作)

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:1)的行数,并使用计算出的行数插入行

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM