如何在 MySQL SELECT 中生成欄位?


為此使用關鍵字 AS。我們先建立一個表 -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20)
   );
Query OK, 0 rows affected (3.16 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.50 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.54 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

輸出

+----+--------+
| Id | Name   |
+----+--------+
| 1  | John   |
| 2  | Robert |
| 3  | David  |
+----+--------+
3 rows in set (0.00 sec)

以下是在 MySQL SELECT 中生成欄位的查詢 -

mysql> select Id,Name,'US' AS CountryName from DemoTable;

輸出

+----+--------+-------------+
| Id | Name   | CountryName |
+----+--------+-------------+
| 1  | John   | US          |
| 2  | Robert | US          |
| 3  | David  | US          | 
+----+--------+-------------+
3 rows in set (0.00 sec)

更新於: 30-7-2019

140 次瀏覽

開啟您的 事業

透過完成課程獲得認證

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