如何从别名中找到mysql中的总和(总和)?

时间:2018-05-31 06:06:01

标签: mysql database mysql-workbench

其实我原来的数据库是

SELECT sum(data1,data2) as database_value,sum(data3,data4) as database_not_value  from table_name;

| ID | science_name_short    |database_value   | database_not_value| 
|  1 | Rhododendron phipli   |3                | 4                 |  
|  2 | Rhododendron felica   |5                |6                  |  
| 3  | Rhododendron deron    |5                | 7                 |   
| 4  | Rhododendron  sednuns |5                |8                  |  

我希望找到第一行,第二行,第三行的总数,并在总列中显示它们,所以我做了

SELECT sum(data1,data2) as database_value,sum(data3,data4) as database_not_value,sum(database_value+database_not_value) as total
  from table_name;

| ID |     science_name_short    |database_value   | database_not_value|Total | 
|  1 | Rhododendron phipli       |3                | 4                 |   7  |
|  2 | Rhododendron felica       |5                |6                  |   11 |
|3   | Rhododendron deron        |5                | 7                 |   12 |
|4   | Rhododendron  sednuns     |5                |8                  |   13 |



 then i get error as column "database_value" does not exist

1 个答案:

答案 0 :(得分:1)

你不能在同一级别的查询中使用别名,要获得总数,你需要重复你的表达

SELECT sum(data1 + data2) as database_value,
sum(data3 + data4) as database_not_value,
sum(data1 + data2) + sum(data3+ data4)  as total
from table_name;

同时sum()采用单个参数,因此我假设您使用+而非逗号

添加数据集