本文介绍了我可以在SELECT查询中重用计算字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以重用mysql语句中的计算字段.我收到错误未知列total_sale"的原因:

Is there a way to reuse a calculated field within a mysql statement. I get the error "unknown column total_sale" for:

SELECT
    s.f1 + s.f2 as total_sale,
    s.f1 / total_sale as f1_percent
FROM sales s

还是我必须重复计算,如果我添加了所有需要的计算,这将导致很长的SQL语句.

or do I have to repeat the calculation, which would make for a very long SQL statement if I added all the calculations I need.

SELECT
    s.f1 + s.f2 as total_sale,
    s.f1 / (s.f1 + s.f2) as f1_percent
FROM sales s

我当然可以在我的php程序中进行所有计算.

of course I can do all the calculations in my php program.

推荐答案

是的,您可以重用变量.这是您的操作方式:

Yes, you can reuse variables. This is how you do it:

SELECT
    @total_sale := s.f1 + s.f2 as total_sale,
    s.f1 / @total_sale as f1_percent
FROM sales s

在此处了解更多信息: http://dev. mysql.com/doc/refman/5.0/en/user-variables.html

Read more about it here: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html

[注意:此行为是未定义的.根据MySQL文档:]

[Note: This behavior is undefined. According to the MySQL docs:]

这篇关于我可以在SELECT查询中重用计算字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:39