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

mysqlmysqli database

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

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

首先我们创建一个表 −

mysql> create table DemoTable
(
   Name varchar(40)
);
Query OK, 0 rows affected (0.62 sec)

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

mysql> insert into DemoTable values('John Smith');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Chris Brown');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('David Miller');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('John Doe');
Query OK, 1 row affected (0.18 sec)

使用 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)

相关文章