2013-05-10 40 views
1

這是我的表votes更有效的方法來做到這一點選擇和更新循環

"id" "votedElm" "voteType" "voteProcessed" "country" 
"3"  "6"   "1"   "0"    "US"//1-1=0 

"4"  "8"   "0"   "0"    "US"//2+0-1=1 
"9"  "8"   "1"   "0"    "US" 

"5"  "9"   "0"   "0"    "US"//2+0-1=1 
"10" "9"   "1"   "0"    "US" 

,這我的表likes

"id"  "type" "parent" "country" "votes" 
    6  10  3   US   1 
    8  10  7   US   2 
    9  10  7   US   2 

我在一個事件這樣做更新表likes

//Pseudocode - This actually is inside an mysql scheduled event 
//Select all the votes 
select id, votedElm, voteType, country from votes 
if voteType = 0 then 

update likes set votes=votes+1 where id=votedElm and country=country 
update votes set voteProcessed = 1 where id = id 

elseif voteType = 1 then 

update likes set votes=votes-1 where id=votedElm and country=country 
update votes set voteProcessed = 1 where id = id 

End If 

這整個事情發生在一次一行。你看到更好更有效的方法來執行sql嗎?

繼承人的事件:

BEGIN 
    DECLARE vId INT(10) DEFAULT '0'; 
    DECLARE vElm INT(10) DEFAULT '0'; 
    DECLARE vType TINYINT(1) DEFAULT '0'; 
    DECLARE vProcessed TINYINT(1) DEFAULT '0'; 
    DECLARE vCountry VARCHAR(2) DEFAULT ""; 
    DECLARE updateDone INT DEFAULT FALSE; 

    -- declare cursor for employee email 
    DEClARE updater CURSOR FOR 
     SELECT id, votedElm, voteType, voteProcessed, country FROM votes; 

    -- declare NOT FOUND handler 
    DECLARE CONTINUE HANDLER 
     FOR NOT FOUND SET updateDone = TRUE; 

    OPEN updater; 

    doUpdate: LOOP 

     FETCH updater INTO vId, vElm, vType, vProcessed, vCountry; 

     IF updateDone THEN 
      LEAVE doUpdate; 
     END IF; 

     -- update likes 
     UPDATE likes 
       INNER JOIN votes 
        ON votes.vElm = likes.id AND votes.vCountry = likes.country 
        SET 
        likes.votes = IF(votes.vType = 0,likes.votes+1,likes.votes-1), 
        votes.vId = 1; 

    END LOOP doUpdate; 

    CLOSE updater; 

END 

回答

3

你可以試試這個:

UPDATE 
    likes 
INNER JOIN votes 
    ON votes.votedElm = likes.id 
    AND votes.country = likes.country 
SET 
    likes.votes = IF(votes.vote_type = 0,likes.votes+1,likes.votes-1), 
    votes.voteProcessed = 1 
WHERE 
    votes.voteProcessed = 0 

您可以閱讀更多有關的多個更新here

+0

我有一個凝灰岩時間讓我的事件內工作。我都對列名和變量名感到困惑。你可以看看我的活動嗎?我在問題中發佈了它。 – Norman 2013-05-10 09:16:29

+0

您正試圖從'votes'表中執行此查詢...但是此查詢會更新所需的所有行,請嘗試單獨執行 – Stephan 2013-05-10 09:19:52

+0

或僅刪除循環,因爲您不需要它 – Stephan 2013-05-10 09:21:13

0

你可以簡單地做3次更新:

update likes set votes=votes+1 where voteType = 0 
update likes set votes=votes-1 where voteType = 1 
update votes set voteProcessed = 1 

假設在這裏,你只有voteType = 0,1,所以你處理所有。

+0

你說得對。 VoteType是0或1 – Norman 2013-05-10 08:20:23

+0

@codedad'where where'? – Shikiryu 2013-05-10 08:23:20

+0

@Shikiryu:糾正,thx! – nzs 2013-05-10 08:28:07

相關問題