我正在尝试做这样的事情。但我得到一个未知的列错误:如何在MySQL中别名字段或列?
SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core
基本上,我想只使用别名,以便我不需要执行前面执行的操作。这可能在MySQL?
我正在尝试做这样的事情。但我得到一个未知的列错误:如何在MySQL中别名字段或列?
SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core
基本上,我想只使用别名,以便我不需要执行前面执行的操作。这可能在MySQL?
考虑使用子查询,如:
SELECT col1
, col1 + field3 AS col3
FROM (
SELECT field1 + field2 as col1
, field3
from core
) as SubQueryAlias
简短的回答是否定的:
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
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.
因此,使用风险自负。
这是甜蜜的语法糖。 :-) – 2011-05-21 11:50:46
+1冷静。我一直使用子查询完成此操作。 – 2011-05-21 12:05:14
不幸的是,这在查询中出色地工作,但不在视图中:( – maxhugen 2013-04-29 02:08:08
根据the spec拉维巴力的回答是不能保证总是工作,为“评价的顺序涉及用户变量是不确定的表述”。
我发现this answer后,我试图使用一个变量,并得到奇怪的结果。
select @code:= SUM(field1 + field2), (@code*1) from abc;
@代号* 1隐蔽到数字表达式,你可以在任何地方使用像
select @code:= SUM(field1 + field2), (@code*1)+field3 from abc;
可以select
别名:
SELECT SUM(field1 + field2) AS col1, (select col1) + field3 AS col3 from core
这工作。
不,这不起作用 – fancyPants 2015-04-16 13:46:49
工作原理同样的问题和相同的解决方案作为这一个:http://stackoverflow.com/questions/2077475/using-an-alias-in-sql-calculations – dxvargas 2015-10-19 15:33:21
这工作很好在mysql ..不知道其他dbs。应该是最佳答案 – billynoah 2016-03-09 20:15:30
'col'从哪里来? – 2011-05-21 11:32:03
错字,它应该是col1 – user225269 2011-05-21 11:34:04
'field3'的什么数据类型? – diEcho 2011-05-21 11:34:19