Can I reuse a calculated field in a SELECT query?(我可以在 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:]
作为一般规则,您永远不应将值分配给用户变量并在同一语句中读取该值.您可能会得到预期的结果,但这并不能保证.
As a general rule, you should never assign a value to a user variable and read the value within the same statement. You might get the results you expect, but this is not guaranteed.
这篇关于我可以在 SELECT 查询中重用计算字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在 SELECT 查询中重用计算字段吗?
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
