在同一 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)
);
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)

更新日期:2019-10-07

677 瀏覽次數

開啟你的 職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.