有人可以看到以下查询有什么问题吗?
当我跑步时,我得到:
#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 在第8行的'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
答案 0 :(得分:128)
主要问题是内部查询无法与外部where
语句上的update
子句相关联,因为where子过滤器首先应用于内部子查询甚至执行之前更新的表。处理这种情况的典型方法是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
答案 1 :(得分:18)
谢谢,我没有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
应该为每个比赛记录提供技巧。
要注意:
效果与mellamokb提出的查询完全不同,后者不会更新没有相应PickPoints的比赛记录。
由于SELECT id, COUNT(*) GROUP BY id
只会计算现有的ID值,
而SELECT COUNT(*)
将始终返回一个值,如果没有选择记录则为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)
换句话说,如果找不到相应的PickPoints,请将Competition.NumberOfTeams设置为零。
答案 2 :(得分:10)
对于不耐烦的人:
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 = t.id
SET t.count = aggregate.count
如上所述,@mellamokb的回答减少到最大值
答案 3 :(得分:0)
您可以检查您的 eav_attributes 表以查找每个图像角色的相关属性 ID,例如;
然后您可以使用这些将任何角色设置为所有产品的任何其他角色,例如;
UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`
以上内容会将您的所有“基本”角色设置为同一产品的“小”图像。