繁体   English   中英

MySQL 如何复用别名创建别名

[英]MySQL how to reuse Alias to create Alias

我在 MySQL 中遇到别名问题,我有一个数据库调用“Table_Profit”,这是我的查询,它工作正常:

$sql="SELECT *,
Profit*24 AS 'Daily_Profit',
Profit*30*24 AS 'Monthly_Profit',
from Table_Profit;

但是现在我想通过使用其他别名添加另一个别名(Total_Profit)并且它不起作用,我该如何解决这个问题?:

$sql="SELECT *,
Profit*24 AS Daily_Profit,
Profit*30*24 AS Monthly_Profit,
Daily_Profit*Monthly_Profit AS Total_Profit
from Table_Profit;

我尝试使用派生表,但它不起作用。

$sql="SELECT *,
Profit*24 AS Daily_Profit,
Profit*30*24 AS Monthly_Profit,
from (
select 
  Daily_Profit*Monthly_Profit AS Total_Profit
from Table_Profit
)AS P;

派生表是执行此操作的一种方法,但您的方法倒退了,因为您在外部而不是内部定义别名。 试试这个版本:

SELECT *, Daily_Profit*Monthly_Profit AS Total_Profit
FROM
(
    SELECT *, Profit*24 AS Daily_Profit, Profit*30*24 AS Monthly_Profit
    FROM Table_Profit
) t;

但在这种情况下,我可能会避免使用子查询,而只是重复少量逻辑:

SELECT *,
    Profit*24 AS Daily_Profit,
    Profit*30*24 AS Monthly_Profit,
    (Profit*24) * (Profit*30*24) AS Total_Profit
FROM Table_Profit;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM