當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


MySQL AS用法及代碼示例


MySQL 的 AS 關鍵字用於重命名列或表或為其提供別名。

用法

-- Alias for column
SELECT column_name AS alias
FROM table_name;
-- Alias for table
SELECT alias.column_name
FROM table_name AS alias;
-- We can also provide a table alias leaving out AS
SELECT alias.column_name
FROM table_name alias;

例子

考慮下表有關一些學生的信息:

student_id

名稱

名字

day_enrolled

年齡

用戶名

1

Sky

Towner

2015-12-03

17

stowner1

2

Ben

Davis

2016-04-20

19

bdavis2

3

Travis

Apple

2018-08-14

18

tapple3

4

Arthur

David

2016-04-01

16

adavid4

5

Benjamin

Town

2014-01-01

17

btown5

可以使用此處的代碼創建上述示例表。

列別名

為列 fnamelnameday_enrolled 提供別名:

SELECT fname AS "First Name", lname AS "Last Name", day_enrolled AS "Day Enrolled"
FROM students;



+------------+-----------+--------------+
| First Name | Last Name | Day Enrolled |
+------------+-----------+--------------+
| Sky        | Towner    | 2015-12-03   |
| Ben        | Davis     | 2016-04-20   |
| Travis     | Apple     | 2018-08-14   |
| Arthur     | David     | 2016-04-01   |
| Benjamin   | Town      | 2014-01-01   |
+------------+-----------+--------------+

這也適用於連接列:

SELECT CONCAT(fname,' ', lname) AS "Full Name", day_enrolled AS "Day Enrolled"
FROM students;



+---------------+--------------+
| Full Name     | Day Enrolled |
+---------------+--------------+
| Sky Towner    | 2015-12-03   |
| Ben Davis     | 2016-04-20   |
| Travis Apple  | 2018-08-14   |
| Arthur David  | 2016-04-01   |
| Benjamin Town | 2014-01-01   |
+---------------+--------------+

表別名

為表 students 提供別名 s

SELECT s.fname, s.lname, s.day_enrolled
FROM students AS s;



+----------+--------+--------------+
| fname    | lname  | day_enrolled |
+----------+--------+--------------+
| Sky      | Towner | 2015-12-03   |
| Ben      | Davis  | 2016-04-20   |
| Travis   | Apple  | 2018-08-14   |
| Arthur   | David  | 2016-04-01   |
| Benjamin | Town   | 2014-01-01   |
+----------+--------+--------------+

在提供表別名時,AS 關鍵字實際上可能被省略:

SELECT s.fname, s.lname, s.day_enrolled
FROM students s;



+----------+--------+--------------+
| fname    | lname  | day_enrolled |
+----------+--------+--------------+
| Sky      | Towner | 2015-12-03   |
| Ben      | Davis  | 2016-04-20   |
| Travis   | Apple  | 2018-08-14   |
| Arthur   | David  | 2016-04-01   |
| Benjamin | Town   | 2014-01-01   |
+----------+--------+--------------+

相關用法


注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 MySQL | AS。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。