在MySQL SELECT语句中,派生字段如何利用SELECT列表中另一个字段的值?
例如,运行以下查询时:
SELECT
'tim' AS first_name
,first_name || ' example' AS full_name;
我希望结果是:
first_name, full_name
tim , tim example
相反,我收到以下错误:
Unknown column 'first_name' in 'field list'.
有没有办法可以引用另一列?
感谢
Turgs
答案 0 :(得分:9)
不,你必须重复它或使用派生表。
select *, concat(first_name, ' example') as full_name
from (
select
'tim' as first_name ) as t
答案 1 :(得分:4)
您可以将查询包装为子查询:
SELECT
first_name
, first_name || ' example' AS full_name
FROM
( SELECT
'tim' AS first_name
, ...
FROM ...
...
) AS tmp
或复制代码:
SELECT
'tim' AS first_name
, 'tim' || ' example' AS full_name
答案 2 :(得分:4)
来自http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html
标准SQL不允许在WHERE子句中引用列别名。强制执行此限制是因为在评估WHERE子句时,可能尚未确定列值。
您无法引用尚未确定其值的列。