Home > Database > Mysql Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-27 02:41:03
Original
226 people have browsed it

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

mysql update query utilizing a subquery

An attempt to update a table using a subquery as part of the SET clause has encountered an error, with the syntax being flagged as incorrect. The specific issue can be attributed to the subsequent WHERE clause in the UPDATE statement.

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
Copy after login

The problem arises because the WHERE filter on the outer update statement executes before the inner subquery. Therefore, the subquery's results cannot be used to filter the table being updated. A common solution to this issue is employing a multi-table update.

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
Copy after login

In this revised query, a multi-table update is used, with Competition as the primary table to be updated (aliased as C). We perform an inner join between Competition and a subquery (aliased as A) that calculates the NumberOfTeams for each CompetitionId. The WHERE clause is now used to filter the join result, ensuring that only matching rows in both tables are updated.

[Demo](http://www.sqlfiddle.com/#!2/a74f3/1) for the updated query.

The above is the detailed content of How to Update a Table with a Subquery in the SET Clause in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!