使用子查询对 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中文网其他相关文章!