温馨提示:本文翻译自stackoverflow.com,查看原文请点击:select - Can i add sum into another sum using only alias in mysql
mysql select

select - 我可以仅使用mysql中的别名将总和添加到另一个总和中吗

发布于 2020-04-09 11:41:49

我有一条这样的声明,其中我需要将多个别名结合为另一个总和并获得输出。

select 
t1.id,
sum(t2.answ = t1.answ) as answerA,
sum(t3.answ = t1.answ) as answerM,
sum(t4.answ = t1.answ) as answerD,
sum(answerA + answerM + answerD) as total
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
group by t1.id // updated

这可能吗?

sum(answerA + answerM + answerD) as total

查看更多

提问者
Dexter
被浏览
31
Barmar 2020-02-01 09:50

不,您不能在同一查询中引用列别名。您将不得不使其成为子查询。

SELECT id, answerA, answerB, answerC, (answerA + answerM + answerD) AS total
FROM (
    select 
        t1.id,
        sum(t2.answ = t1.answ) as answerA,
        sum(t3.answ = t1.answ) as answerM,
        sum(t4.answ = t1.answ) as answerD,
        sum(answerA + answerM + answerD) as total
    from t1
    left join t2 on t2.id = t1.t2fk
    left join t3 on t3.id = t1.t3fk
    left join t4 on t4.id = t1.t4fk
    GROUP BY t1.id
) AS subquery

或者您可以编写一个等效的表达式。

select 
    t1.id,
    sum(t2.answ = t1.answ) as answerA,
    sum(t3.answ = t1.answ) as answerM,
    sum(t4.answ = t1.answ) as answerD,
    sum(t1.answ IN (t2.answ, t3.answ, t4.answ)) as total
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
GROUP BY t1.id

最新帖子

最新文章