2011-05-21 20 views
23

我正在尝试做这样的事情。但我得到一个未知的列错误:如何在MySQL中别名字段或列?

SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core 

基本上,我想只使用别名,以便我不需要执行前面执行的操作。这可能在MySQL?

+0

'col'从哪里来? – 2011-05-21 11:32:03

+0

错字,它应该是col1 – user225269 2011-05-21 11:34:04

+0

'field3'的什么数据类型? – diEcho 2011-05-21 11:34:19

回答

13

考虑使用子查询,如:

SELECT col1 
,  col1 + field3 AS col3 
FROM (
     SELECT field1 + field2 as col1 
     ,  field3 
     from core 
     ) as SubQueryAlias 
2

简短的回答是否定的:

mysql> select 1 as a, a + 1 as b; 
ERROR 1054 (42S22): Unknown column 'a' in 'field list' 

postgresql# select 1 as a, a + 1 as b; 
ERROR: column "a" does not exist 

这就是说,一些SQL实现允许/ having子句使用其中/组的别名,如:

postgresql# select 1 as a group by a; -- 1 row 
33

select @code:= SUM(field1 + field2), @code+1 from abc;

但请注意以下内容(来自MySQL 5.6 docs):

As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:

SET @a = @a + 1; 

For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second:

SELECT @a, @a:[email protected]+1, ...; 

However, the order of evaluation for expressions involving user variables is undefined.

因此,使用风险自负。

+0

这是甜蜜的语法糖。 :-) – 2011-05-21 11:50:46

+0

+1冷静。我一直使用子查询完成此操作。 – 2011-05-21 12:05:14

+0

不幸的是,这在查询中出色地工作,但不在视图中:( – maxhugen 2013-04-29 02:08:08

4

根据the spec拉维巴力的回答是不能保证总是工作,为“评价的顺序涉及用户变量是不确定的表述”。

我发现this answer后,我试图使用一个变量,并得到奇怪的结果。

3
select @code:= SUM(field1 + field2), (@code*1) from abc; 

@代号* 1隐蔽到数字表达式,你可以在任何地方使用像

select @code:= SUM(field1 + field2), (@code*1)+field3 from abc; 
+0

我来这里投票给你,这在我们的场景中完美运作。用更匈牙利/代码风格的友好变量替换@code并保留AS。 '@fVariable:= SUM(column)AS alias'(别名应该用反引号括起来,所以SO不能正确渲染它们) – ReSpawN 2016-06-07 10:31:18

+0

@ReSpawN这是不确定的行为,它恰好给了你预期的答案,因为它是开放源代码,如果您检查代码,某些读取和写入用法对于特定版本是安全的(如果您不认为这是矛盾的话) – philipxy 2017-08-16 01:51:13

12

可以select别名:

SELECT SUM(field1 + field2) AS col1, (select col1) + field3 AS col3 from core 

这工作。

+0

不,这不起作用 – fancyPants 2015-04-16 13:46:49

+2

工作原理同样的问题和相同的解决方案作为这一个:http://stackoverflow.com/questions/2077475/using-an-alias-in-sql-calculations – dxvargas 2015-10-19 15:33:21

+3

这工作很好在mysql ..不知道其他dbs。应该是最佳答案 – billynoah 2016-03-09 20:15:30