gpt4 book ai didi

mysql - 我可以在 SELECT 查询中重复使用计算字段吗?

转载 作者:IT老高 更新时间:2023-10-28 12:54:07 27 4
gpt4 key购买 nike

有没有办法在 mysql 语句中重用计算字段。我收到以下错误“未知列 total_sale”:

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

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

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

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

最佳答案

是的,您可以重复使用变量。这就是你的做法:

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

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

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.

关于mysql - 我可以在 SELECT 查询中重复使用计算字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6085443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com