2012-08-27 45 views
1

在嘗試此查詢:爲什麼我會得到這個錯誤在我的SQL查詢

UPDATE l1_a 
SET l1_a.goals_for = l1_a.goals_for + l1_results.score1 
FROM l1_results, l1_a 
WHERE l1_results.team1 = l1_a.team_id; 

我得到的錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM l1_results, l1_a WHERE l1_results.team1 = l1_a.team_id' at line 3 

l1_a包含goals_for和TEAM_ID

l1_results包含score1(這是多少goal_for)和team1(這是team_id)

我的曲線有什麼問題ERY?我有雙重檢查,所有的列和表是正確的名稱查詢

感謝

+3

你不能在更新了 「FROM」 子句。 – feathj

+1

@jonfen - 這取決於關係型數據庫,雖然這看起來像MySQL,所以你的評論將是正確的 – Lamak

回答

4

documentation for UPDATE狀態,這是語法多表UPDATE聲明:

Multiple-table syntax: 

UPDATE [LOW_PRIORITY] [IGNORE] table_references 
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... 
    [WHERE where_condition] 

試試這個:

UPDATE l1_results, l1_a 
SET l1_a.goals_for = l1_a.goals_for + l1_results.score1 
WHERE l1_results.team1 = l1_a.team_id; 
+0

UPDATE l1_results,l1_a SET l1_a.goals_for = l1_a.goals_for + l1_results.score1 WHERE l1_results.team1 = l1_a.team_id; 完美運作,謝謝! – Koala

1

你結合選擇和更新的語法。更新語句中沒有from

試試這個:

UPDATE l1_a 
SET l1_a.goals_for = l1_a.goals_for + 
    (select l1_results.score1 
    from l1_results 
    where l1_results.team1 = l1a.team_id) 

如果有在l1_results沒有記錄,你可能會清空您的數據。最好加一個IFNULL:

UPDATE l1_a 
SET l1_a.goals_for = l1_a.goals_for + IFNULL(
    (select l1_results.score1 
    from l1_results 
    where l1_results.team1 = l1a.team_id), 0) 
+0

感謝您的回覆,有沒有做這個查詢沒有FROM? – Koala

+0

我這麼認爲。我已經添加了一個聲明,但目前我無法測試它。 – GolezTrol

+1

@GolezTrol不要這樣做 - 只需使用多表更新語法即可。 – Ariel

0

變化

UPDATE l1_a 
SET l1_a.goals_for = l1_a.goals_for + l1_results.score1 
FROM l1_results, l1_a 
WHERE l1_results.team1 = l1_a.team_id; 

UPDATE l1_a 
SET l1_a.goals_for = l1_a.goals_for + l1_results.score1 
WHERE l1_results.team1 = l1_a.team_id; 

你不需要FROM l1_results,l1_a