[英]Timing issue on mySQL INSERT with TRIGGER
For an iPad app I have created a web service which creates a new table row in my teams table when the user starts the app. 对于iPad应用程序,我创建了一个Web服务,当用户启动该应用程序时,该服务会在我的teams表中创建一个新表行。 The PHP generates a unique ID and fills some other fields as well. PHP生成唯一的ID,并填充其他一些字段。
Additionally I have created a trigger on the teams table in mySQL on insert where a teamnumber is generated automatically depending on the already inserted rows for that specific day, project and group. 另外,我在插入时在mySQL的teams表上创建了一个触发器,其中会根据该特定日期,项目和组的已插入行自动生成teamnumber。
Unfortunately I seem to have a timing issue when inserting new rows to my table sometimes. 不幸的是,有时在向表中插入新行时似乎存在时间问题。 If two apps create a team in the same second (milisecond?) the result of the mySQL trigger will be the same teamnumber for both apps. 如果两个应用程序在同一秒(毫秒)内创建了一个团队,则mySQL触发器的结果将是两个应用程序的团队编号相同。 So instead of having teamnumber 1 and 2 both apps have teamnumber 1. 因此,两个应用程序都没有团队号1和2,而是团队号1。
My teamtable looks something like this: 我的团队表如下所示:
TeamID | pProject | group | teamnumber | languagecode | created_at
And the trigger for mySQL: 以及mySQL的触发器:
CREATE TRIGGER after_team_insert BEFORE INSERT ON teams
FOR EACH ROW
BEGIN
SELECT COUNT( * ) INTO @counter
FROM teams
WHERE DATE( created_at ) = DATE( NOW( ) )
AND teams.group = NEW.group
AND teams.pProject = NEW.pProject;
SET NEW.teamnumber = CAST(@counter AS UNSIGNED) + 1;
END;
I think my problem has something to do with parallel threads that insert rows into the database and therefor get a wrong count when the trigger is working. 我认为我的问题与在数据库中插入行的并行线程有关,因此在触发器工作时计数错误。
Does anyone have a solution for this problem or do I have to use some kind of queue in PHP to prevent this doubling of teamnumbers? 有没有人有解决此问题的方法,还是我必须在PHP中使用某种队列来防止组号增加一倍?
Thanks in advance, Carsten. 在此先感谢Carsten。
I guess you can use a lock table ! 我猜你可以使用锁表! http://dev.mysql.com/doc/refman/5.0/fr/lock-tables.html http://dev.mysql.com/doc/refman/5.0/fr/lock-tables.html
If, for any reason, you can't lock your table you can try to handle the problem differently: 如果由于某种原因无法锁定表,则可以尝试以其他方式处理该问题:
Not that clean, a bit tricky, but it should do the work if you don't mind team number 3 was inserted after team number 4. 不是很干净,有点棘手,但是如果您不介意在第4队之后插入第3队,它应该可以完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.