如何在 MySQL 中使用 SET 子句中的子查詢更新表?

Mary-Kate Olsen
發布: 2024-10-27 02:41:03
原創
226 人瀏覽過

How to Update a Table with a Subquery in the SET Clause in MySQL?

利用子查詢的mysql 更新查詢

嘗試使用子查詢作為SET 子句的一部分來更新表時遇到了錯誤,語法被標記為不正確。具體問題可以歸因於 UPDATE 語句中後續的 WHERE 子句。

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
  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
登入後複製

在這個修改後的查詢中,使用多表更新,其中 Comparison 作為要更新的主表(別名為 C) 。我們在Competition和子查詢(別名為A)之間執行內部聯接,計算每個CompetitionId的NumberOfTeams。 WHERE 子句現在用於過濾聯結結果,確保只更新兩個表中的符合行。

[示範](http://www.sqlfiddle.com/#!2/a74f3/1 ) 取得更新後的查詢。

以上是如何在 MySQL 中使用 SET 子句中的子查詢更新表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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