2013-05-19 66 views
0
"id" "type" "parent" "country" "votes" "perCent" 
    "1"  "1"  "0"   "US"  "100"  "0" 
    "2"  "1"  "0"   "US"  "50"  "0" 
    "3"  "100" "0"   "US"  "150"  "0" ->150 = sum(votes) where type = 1 and country = country 
    "4"  "1"  "0"   "SE"  "50"  "0" 
    "5"  "1"  "0"   "SE"  "25"  "0" 
    "6"  "100" "0"   "SE"  "75"  "0" ->75 = sum(votes) where type = 1 and country = country 

我試圖更新type=100所有type=1爲各自國家的總和()。的MySQL更新行

我一直在努力與這個SQL,似乎無處可去。基本上,我想要做的是更新投票,其中type = 100與他們各自國家的類型總和= 1。 我一直在試圖調整這一點,但似乎完全失敗。你能幫忙嗎?

UPDATE likes p 
JOIN likes h 
    ON p.country = h.country 
    AND (p.type=1) AND h.type=1 
SET p.votes=sum(h.votes) where p.type=100; 

回答

2
UPDATE tableName a 
     INNER JOIN 
     (
      SELECT country, SUM(votes) totalVotes 
      FROM tableName 
      WHERE type = 1 
      GROUP BY country 
     ) b ON a.country = b.country 
SET  a.votes = b.totalVotes 
WHERE a.type = 100