72

任何人都可以看到以下查询有什么问题吗?

当我运行它时,我得到:

#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
4

4 回答 4

171

主要问题是内部查询不能与where外部update语句上的子句相关,因为 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

演示:http ://www.sqlfiddle.com/#!2/a74f3/1

于 2012-07-21T01:24:43.747 回答
23

谢谢,我没有使用 INNER JOIN 进行更新的想法。

在原始查询中,错误是为子查询命名,它必须返回一个值,因此不能使用别名。

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 值,

而 aSELECT COUNT(*)将始终返回一个值,如果没有选择记录,则为 0。

这可能对您来说是个问题,也可能不是。

mellamokb 查询的 0 感知版本将是:

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 设置为零。

于 2013-09-04T12:37:50.743 回答
15

对于不耐烦的人:

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的答案,已降至最大值。

于 2016-01-16T05:53:13.183 回答
0

您可以检查您的 eav_attributes 表以查找每个图像角色的相关属性 ID,例如; eav_attributes

然后,您可以使用它们将任何角色设置为所有产品的任何其他角色;

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`

以上会将您所有的“基本”角色设置为同一产品的“小”图像。

于 2021-01-08T15:59:42.660 回答