当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。