在同一MySQL SELECT语句中使用别名的值

您不能在SELECT中直接使用别名。而是使用用户定义的变量。以下是语法。在这里,@yourAliasName是我们的变量和别名-

select @yourAliasName :=curdate() as anyAliasName,concat(‘yourValue.',yourColumnName,' yourValue',@yourAliasName) as anyAliasName from yourTableName;

让我们首先创建一个表-

mysql> create table DemoTable
(
   Name varchar(40)
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values('John Smith');
mysql> insert into DemoTable values('Chris Brown');
mysql> insert into DemoTable values('David Miller');
mysql> insert into DemoTable values('John Doe');

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

这将产生以下输出-

+--------------+
| Name         |
+--------------+
| John Smith   |
| Chris Brown  |
| David Miller |
| John Doe     |
+--------------+
4 rows in set (0.00 sec)

以下是在同一SQL语句中使用别名值的查询-

mysql> select @todayDate :=curdate() as todayDate,concat('Mr.',Name,' The current Date is=',@todayDate) as Result from DemoTable;

这将产生以下输出-

+------------+------------------------------------------------+
| todayDate  | Result                                         |
+------------+------------------------------------------------+
| 2019-09-08 | Mr.John Smith The current Date is=2019-09-08   |
| 2019-09-08 | Mr.Chris Brown The current Date is=2019-09-08  |
| 2019-09-08 | Mr.David Miller The current Date is=2019-09-08 |
| 2019-09-08 | Mr.John Doe The current Date is=2019-09-08     |
+------------+------------------------------------------------+
4 rows in set (0.00 sec)