sql设置和在select语句中使用变量

时间:2015-04-16 09:34:12

标签: mysql sql

比如说你有以下sql:

SELECT 
    attempt.user_id,
    attempt.team_id,
    SUM(CASE
        WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN attempt.score
    END) / COUNT(CASE
        WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN 1
    END) as avg_score,
    (SELECT 
            COUNT(atha.academy_module_id)
        FROM
            academy_team_has_academy_module atha
        WHERE
            atha.academy_team_id = attempt.team_id
    ) as num_modules

FROM
    academy_attempt attempt
GROUP BY attempt.user_id

现在您希望使用num_modules执行以下操作:

    num_modules / COUNT(attempt.module_id) as completed

当我运行时,我得到(正如预期的那样)Unknown column num_modules

那么有什么方法可以将它设置为变量,所以我可以使用该值吗?

2 个答案:

答案 0 :(得分:1)

您可以更改

(SELECT 
        COUNT(atha.academy_module_id)
    FROM
        academy_team_has_academy_module atha
    WHERE
        atha.academy_team_id = attempt.team_id
) as num_modules

@num_modules:=(SELECT 
        COUNT(atha.academy_module_id)
    FROM
        academy_team_has_academy_module atha
    WHERE
        atha.academy_team_id = attempt.team_id
) as num_modules

然后您可以使用@num_modules后缀作为变量。

就像@num_modules / COUNT(attempt.module_id) as completed

一样

答案 1 :(得分:1)

我认为这样做的方法是做一个像这样的子查询:

SELECT
    tbl.user_id,
    tbl.team_id,
    tbl.num_modules / tbl.countModule_id as completed,
    tbl.avg_score,
    tbl.num_modules
FROM
(
    SELECT 
        attempt.user_id,
        attempt.team_id,
        SUM(CASE
            WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN attempt.score
        END) / COUNT(CASE
            WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN 1
        END) as avg_score,
        (SELECT 
                COUNT(atha.academy_module_id)
            FROM
                academy_team_has_academy_module atha
            WHERE
                atha.academy_team_id = attempt.team_id
        ) as num_modules,
        COUNT(attempt.module_id) as countModule_id
    FROM
        academy_attempt attempt
    GROUP BY attempt.user_id
) as tbl