1

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

 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

4

3 回答 3

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
于 2013-11-23T17:26:28.457 回答
0

您可以简化UPDATE. 请参阅SQL 小提琴

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表(对于那些没有玩过游戏的用户使用 Nulls),而只是那些在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 ;
于 2013-11-23T17:32:04.620 回答
0

尝试在子查询中添加过滤条件。您在评论中提到的错误“子查询返回超过 1 行”意味着子查询(您命名为 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
于 2013-11-24T01:13:41.890 回答