MySql"未知栏"在子查询中

时间:2016-11-14 09:24:04

标签: mysql greatest-n-per-group

我收到此查询的Unknown column 's.UserId' in 'where clause'错误

SELECT s.UserId, u.name, COUNT(v.FieldValue) as score_count,
(
    SELECT SUM(score) FROM
    (
        #Unknown column 's.UserId' in 'where clause'
        SELECT v2.FieldValue AS `score` FROM submission_values AS v2
        LEFT JOIN submissions AS s2 ON v2.SubmissionId = s2.SubmissionId
        WHERE s2.confirmed = '1' AND v2.FormId = 4 AND v2.FieldName = 'GOLF_SCORE' AND s2.UserId = s.UserId
        ORDER BY v2.FieldValue DESC LIMIT 10
    ) AS `score_sum`
) AS `score_sum`
FROM submission_values AS v
LEFT JOIN submissions AS s ON v.SubmissionId = s.SubmissionId
LEFT JOIN users AS u ON s.UserId = u.id
WHERE s.confirmed = '1' AND v.FormId = '{$formId}' AND v.FieldName = 'GOLF_SCORE'
AND s.DatePlayed >= '2016-02-06 11:18:37'
GROUP BY s.UserId ORDER BY score_sum DESC, score_count DESC LIMIT 20

我理解MySql不支持选择部分中的嵌套子查询,但我需要嵌套它以选择每个用户的前10个分数中的SUM。有没有办法修改此查询,因此它不是子查询?

编辑:这里有一些示例数据

submissions table
--------------------------------------------------
SubmissionId | UserId  | confirmed | DatePlayed
--------------------------------------------------
     1       |   12    |     1     | some date string
     2       |   14    |     1     | some date string
     3       |   12    |     1     | some date string
     4       |   12    |     1     | some date string


submission_values table
-------------------------------------------
 id | SubmissionId | FieldName | FieldValue
-------------------------------------------
  1 |     1        | GOLF_SCORE|  80
  2 |     2        | GOLF_SCORE|  100
  3 |     3        | GOLF_SCORE|  120
  4 |     4        | GOLF_SCORE|  140

预期结果: 我有一个包含数百名玩家的桌子,我希望根据他们排名前10位的总和来创建前20名玩家的排行榜。

使用目前已尝试的内容进行编辑:

        SELECT s.UserId, u.name, COUNT(v.FieldValue) as score_count,
        SUM(x.FieldValue) AS score_sum FROM
        (
            SELECT s2.*, v2.FieldValue FROM submission_values AS v2
            LEFT JOIN submissions AS s2 ON v2.SubmissionId = s2.SubmissionId
            WHERE s2.confirmed = '1' AND v2.FormId = '{$formId}' AND v2.FieldName = 'GOLF_SCORE'
            GROUP BY v2.SubmissionValueId, s2.SubmissionId
            ORDER BY v2.FieldValue DESC LIMIT 10
        ) AS `x`
        LEFT JOIN submissions AS s ON x.UserId = s.UserId
        LEFT JOIN submission_values AS v ON s.SubmissionId = v.SubmissionId
        LEFT JOIN users AS u ON s.UserId = u.id
        WHERE s.confirmed = '1' AND v.FormId = '{$formId}' AND v.FieldName = 'GOLF_SCORE' AND s.UserId = x.UserId
        AND s.DatePlayed >= '2016-02-06 11:18:37'
        GROUP BY s.UserId ORDER BY score_sum DESC, score_count DESC LIMIT 20

0 个答案:

没有答案