MySQL:如何将当前 select 语句中创建的两个字段的结果相加?

Posted

技术标签:

【中文标题】MySQL:如何将当前 select 语句中创建的两个字段的结果相加?【英文标题】:MySQL: How to add the result of two fields created in the current select statement? 【发布时间】:2011-06-29 16:34:54 【问题描述】:

我正在创建一个 mysql 视图表,所以到目前为止我的代码看起来像这样:

CREATE VIEW `myview`
AS SELECT
    (do some stuff here) AS `Revenue1`,
    (do some more here)  AS `Revenue2`
FROM ...

现在我想添加一个列是这两个字段的总和,所以我尝试了这个:

CREATE VIEW `myview`
AS SELECT
    (do some stuff here) AS `Revenue1`,
    (do some more here)  AS `Revenue2`,
    (`Revenue1` + `Revenue2`) AS `TotalRevenue`
FROM ...

但这会导致错误提示 Revenue1 字段未知。如何添加这两个字段并将结果作为新列获取?

【问题讨论】:

【参考方案1】:

你必须重复以下内容:

CREATE VIEW `myview`
AS SELECT
    (do some stuff here) AS `Revenue1`,
    (do some more here)  AS `Revenue2`,
    ((do some stuff here) + (do some more here)) AS `TotalRevenue`
FROM ...

或创建第二个视图:

CREATE VIEW `myview_Two`
AS SELECT
    `Revenue1`,
    `Revenue2`,
    `Revenue1` + `Revenue2` AS `TotalRevenue`
FROM myview

【讨论】:

【参考方案2】:

我认为这应该可行:

CREATE VIEW `myview` 
AS 
  SELECT 
       (do some stuff here) AS `Revenue1`,     
       (do some more here)  AS `Revenue2`,     
       (do some stuff here) + (do some more here) AS `TotalRevenue`
  FROM ... 

【讨论】:

看到这个***.com/questions/206062/… 你每天都会学到新东西。答案已更新.. 虽然必须有更好的方法来做到这一点......

以上是关于MySQL:如何将当前 select 语句中创建的两个字段的结果相加?的主要内容,如果未能解决你的问题,请参考以下文章

如何将在我的数据库中创建的特定行列入黑名单?

Mysql:如何将数据添加到存储在变量中的现有数据中?

如何在MySQL中创建视图

MySQL select 语句 - 如何计算当前排名

我们如何在 MySQL 工作台模式部分查看在 phpmyadmin 中创建的数据库/表?

如何在 php 中创建安全的 mysql 准备语句?