在 MySQL 中更新資料時,通常需要使用子查詢來引用其他表格中的值。但是,當子查詢與外部更新語句沒有正確關聯時,可能會發生錯誤。
考慮以下查詢:
Update Competition Set Competition.NumberOfTeams = ( SELECT count(*) as NumberOfTeams FROM PicksPoints where UserCompetitionID is not NULL group by CompetitionID ) a where a.CompetitionID = Competition.CompetitionID
此查詢失敗並顯示錯誤訊息:
#1064 - 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 'a where a.CompetitionID = Competition.CompetitionID' at line 8
出現錯誤是因為內部子查詢與外部更新語句上的where 子句不相關。在執行子查詢之前,where 條件適用於目標表(Competition)。為了解決這個問題,可以採用多表更新:
Update Competition as C inner join ( select CompetitionId, count(*) as NumberOfTeams from PicksPoints as p where UserCompetitionID is not NULL group by CompetitionID ) as A on C.CompetitionID = A.CompetitionID set C.NumberOfTeams = A.NumberOfTeams
這個多表更新正確地將競爭表(別名為C)與子查詢(別名為A)連接起來,確保子查詢的值可用於在外部更新語句中進行篩選。
有關更正查詢的現場演示,請參閱以下 SQL Fiddle:http://www.sqlfiddle.com/#!2/a74f3/ 1
以上是如何在MySQL更新語句中正確使用子查詢以避免語法錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!