MySQL更新查询与子查询
任何人都可以看到下面的查询有什么问题吗?
当我运行它时,我得到:
#1064 – 你的SQL语法错误; 检查对应于您的MySQL服务器版本的手册,以便在第8行'a where a.CompetitionID = Competition.CompetitionID'附近使用正确的语法
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
主要的问题是内部查询无法与外部update
语句的where
子句相关,因为在内部子查询甚至执行之前,wherefilter首先应用于正在更新的表。 处理这种情况的典型方法是多表更新 。
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
演示: http ://www.sqlfiddle.com/#!2/ a74f3/1
谢谢,我没有与INNER JOIN UPDATE的想法。
在原来的查询中,错误的是命名子查询,它必须返回一个值,因此不能被别名。
UPDATE Competition SET Competition.NumberOfTeams = (SELECT count(*) -- no column alias FROM PicksPoints WHERE UserCompetitionID is not NULL -- put the join condition INSIDE the subquery : AND CompetitionID = Competition.CompetitionID group by CompetitionID ) -- no table alias
应该为每个竞争logging做好诀窍。
要注意的是:
这个效果和美乐公司提出的查询不完全一样,它不会更新竞赛logging,也没有相应的选点。
由于SELECT id, COUNT(*) GROUP BY id
将仅计入ID的现有值,
而SELECT COUNT(*)
将始终返回值,如果没有selectlogging,则为0。
这可能会或可能不会成为你的问题。
0知道版本的mellamokb查询将是:
Update Competition as C LEFT 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 = IFNULL(A.NumberOfTeams, 0)
换句话说,如果找不到相应的PickPoint,将Competition.NumberOfTeams设置为零。
对于急躁:
UPDATE target AS t INNER JOIN ( SELECT s.id, COUNT(*) AS count FROM source_grouped AS s -- WHERE s.custom_condition IS (true) GROUP BY s.id ) AS aggregate ON aggregate.id = target.id SET t.count = aggregate.count
这是@mellamokb的答案,如上所述,减less到最大。