如何在MySQL更新語句中正確使用子查詢以避免語法錯誤?

Patricia Arquette
發布: 2024-10-26 17:37:30
原創
490 人瀏覽過

How to Properly Use Subqueries in MySQL Update Statements to Avoid Syntax Errors?

了解更新查詢中的 SQL 子查詢

在 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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!