首頁  >  文章  >  資料庫  >  如何修復 MySQL 使用子查詢更新查詢中的「錯誤 #1064:您的 SQL 語法有錯誤」?

如何修復 MySQL 使用子查詢更新查詢中的「錯誤 #1064:您的 SQL 語法有錯誤」?

Patricia Arquette
Patricia Arquette原創
2024-10-26 12:06:29667瀏覽

How to Fix

使用子查詢對MySQL 更新查詢進行故障排除

在使用子查詢的MySQL 更新查詢中,您可能會遇到類似以下的錯誤:

#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

查詢:

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

問題:

出現錯誤是因為外部的where 子句update 語句(其中a.CompetitionID = Competition.CompetitionID)無法連結到內部子查詢。在執行內部子查詢之前,將 where 篩選器套用至正在更新的表(競爭)。

解決方案:

要解決此問題,請使用多表更新:

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)連接起來,該子查詢計算每場比賽。加入條件位於CompetitionID 上。然後,更新語句將競賽表中的 NumberOfTeams 欄位設定為子查詢的計算值。

示範:

您可以在SQL Fiddle 上嘗試此更新的查詢:http://www.sqlfiddle.com/#!2/a74f3/1

以上是如何修復 MySQL 使用子查詢更新查詢中的「錯誤 #1064:您的 SQL 語法有錯誤」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn