简体   繁体   English

在同一条sql语句中使用别名的值

[英]Using the value of an alias inside the same sql statement

How can I use the value of an alias for display in the same sql statement? 如何使用别名的值在同一sql语句中显示?

For example: 例如:

select now() as t, concat('Hello: ', username, t) from table;

What I'm actually trying to do is a lot more complex. 我实际上想做的事情要复杂得多。 I've broken it down to this so you get the idea. 我将其分解为这样,以便您理解。

How can something like this be done so I neednt select the same column again? 怎么做这样的事情,所以我不必再次选择同一列?

You can not do that directly, but there's a way in MySQL to use variables like this: 您不能直接这样做,但是MySQL中有一种方法可以使用如下变量:

select @t:=now() as t, concat('Hello: ', username, @t) from t;

If you don't need this t - you may want to remove that alias (I've kept just in case) 如果您不需要此t ,则可能要删除该别名(以防万一)

You can't re-use directly an alias in the select part of the same level of query. 您不能在相同级别的查询的选择部分中直接重复使用别名。

You could use 你可以用

a variable 一个变量

select @myVar := now(), concat('Hello:', username, @myVar) from t;

a subquery 子查询

select concat('Hello:', username, t)
from (select now() as t, username from table1) s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM