使用update连接表时,操作数应包含1列

时间:2013-11-23 17:10:37

标签: mysql mysql-error-1241

我正在尝试通过组合两个查询来更新表,如下所示

 UPDATE result, games_played
      SET result.precentage_correct =
(
SELECT user_id, 100*SUM(n_win)/SUM(n_total) AS pct_win FROM
(SELECT user_id, COUNT(user_id) AS n_win,
  NULL AS n_total
  FROM games_played
  WHERE winner != 'n'
  AND game = 1
  GROUP BY user_id
  UNION SELECT user_id, NULL AS n_win,
  COUNT(user_id) AS n_total
  FROM games_played
  WHERE game = 1
  GROUP BY user_id
) AS counts
GROUP BY counts.user_id
)
WHERE result.user_id = games_played.user_id

但是我收到了错误

Operand should contain 1 column(s)

有谁知道我做错了什么......我可以选择结果作为新表

SQL小提琴http://sqlfiddle.com/#!2/5374e6/1

3 个答案:

答案 0 :(得分:0)

我对查询的逻辑不是很确定,但你可以通过在源表列表中对它进行别名来实际使用查询作为表来修复语法错误。

http://sqlfiddle.com/#!2/436eb/1

UPDATE result, games_played,
  (SELECT t1.user_id, 100*SUM(t1.n_win)/SUM(t1.n_total) AS pct_win FROM
   (SELECT user_id, COUNT(user_id) AS n_win, NULL AS n_total
     FROM games_played
     WHERE winner != 'n' AND game = 1
     GROUP BY user_id
    UNION 
    SELECT user_id, NULL AS n_win, COUNT(user_id) AS n_total
     FROM games_played
     WHERE game = 1
     GROUP BY user_id
   ) AS t1
  ) AS counts

SET result.precentage_correct = counts.pct_win
WHERE result.user_id = games_played.user_id

答案 1 :(得分:0)

您可以简化UPDATE。请参阅SQL-Fiddle

UPDATE result
SET result.precentage_correct =
    ( SELECT 100*SUM(winner <> 'n')/COUNT(*) AS pct_win
      FROM games_played
      WHERE game = 1
        AND result.user_id = games_played.user_id
    ) ;

或者查询更像您的逻辑。这甚至更好,因为(与之前不同)它不会UPDATE整个result表(对于那些没有玩过游戏的用户来说只有Null)而只有那些至少有一个结果的用户games_played表。在SQL-Fiddle-2

进行测试
UPDATE result AS r
  JOIN
    ( SELECT user_id, 
             100*SUM(winner <> 'n')/COUNT(*) AS pct_win
      FROM games_played
      WHERE game = 1
      GROUP BY user_id
    ) AS gp
    ON r.user_id = gp.user_id
SET r.precentage_correct = gp.pct_win ;

答案 2 :(得分:0)

尝试在子查询中添加过滤条件。您在注释中提到的错误“子查询返回多于一行”意味着子查询(您命名为AS计数的那个)返回了多个结果。像这样:

UPDATE result, games_played
      SET result.precentage_correct =
(
SELECT 100*SUM(n_win)/SUM(n_total) AS pct_win FROM
(SELECT user_id, COUNT(user_id) AS n_win,
  NULL AS n_total
  FROM games_played
  WHERE winner != 'n'
  AND game = 1
  GROUP BY user_id
  UNION SELECT user_id, NULL AS n_win,
  COUNT(user_id) AS n_total
  FROM games_played
  WHERE game = 1
  GROUP BY user_id
) AS counts
GROUP BY counts.user_id
HAVING counts.user_id = result.user_id
)
WHERE result.user_id = games_played.user_id