的問題是,如果兩個不同的用戶票同時它可能是 代碼的兩個實例嘗試插入一個新的ID(或類似類型的查詢),將給出一個埃羅
是的,您最終可能會執行兩次插入操作。根據表上的約束條件,其中一個會產生一個錯誤,或者最終會在數據庫中出現兩行。
你可以解決這個,我相信,應用一些鎖定; 例如如果你需要一個投票添加到產品ID爲theProductId:(僞代碼)
START TRANSACTION;
//lock on the row for our product id (assumes the product really exists)
select 1 from products where id=theProductId for update;
//assume the vote exist, and increment the no.of votes
update votes set numberOfVotes = numberOfVotes + 1 where productId=theProductId ;
//if the last update didn't affect any rows, the row didn't exist
if(rowsAffected == 0)
insert into votes(numberOfVotes,productId) values(1,theProductId)
//insert the new vote in the per user votes
insert into user_votes(productId,userId) values(theProductId,theUserId);
COMMIT;
一些更多的信息here
MySQL提供了另一種解決方案爲好,這可能是適用在這裏,insert on duplicate
例如你也許可以只是做:
insert into votes(numberOfVotes,productId) values(1,theProductId) on duplicate key
update numberOfVotes = numberOfVotes + 1;
如果您的投票表對產品ID列的唯一鑰匙,上面會 執行插入如果特定theProductId不存在,否則會做一個更新,其中numberOfVotes列增加1
如果在將產品添加到數據庫的同時在票據表中創建了一行,則可能會避免很多此類情況。這樣你可以確定你的產品總是有一排,只需在該行上發佈UPDATE。
來源
2010-10-03 22:47:04
nos
它可能有助於顯示您的表結構(表/列名) – rojoca 2010-10-03 22:21:38
我只是舉一個例子,但爲了幫助您:product_votes表有一個productID,一個votes_count和一個total_votes_value列。 user_product_votes表有一個userID,一個productID和一個user_vote列.. – Jonathan 2010-10-03 23:05:50
我問的唯一原因是在這個例子中,重新組織你的邏輯和表結構似乎會更好,因此同時插入並不重要,而不是試圖阻止他們。你是問一個普遍的問題還是你需要解決你的例子中的具體問題? – rojoca 2010-10-03 23:26:04