MariaDB 关键字

MariaDB AS 关键字用于别名语句中,用于为表的列、聚合函数列或表本身提供临时名称。别名仅在查询期间存在。它有助于轻松理解名称,从而提高 MariaDB 代码的可读性。

语法

在 MariaDB 中使用 AS 关键字的语法如下:

/* 列的别名 */
SELECT column_name AS AS_name
FROM table_name;

/* 聚合函数的别名 */
SELECT SUM(column_name) AS ALIAS_name
FROM table_name
WHERE condition(s);

/* 表的别名 */
SELECT ALIAS_name_1.column1, ALIAS_name_2.column1, ...
FROM table1 AS ALIAS_name_1
INNER JOIN table2 AS ALIAS_name_2
ON 别名_name_1.matching_column = ALIAS_name_2.matching_column; 

示例:

考虑一个数据库,其中包含名为 Employee 和 Contact_Info 的表,并具有以下记录:

表1:Employee 

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

表2:Contact_Info表

Phone_NumberEmpIDAddressGender
+1-80540980002Brooklyn, New York, USAF
+33-1479961013Grenelle, Paris, FranceM
+31-2011503194Geuzenveld, Amsterdam, NetherlandsF
+86-10997324586Yizhuangzhen, Beijing, ChinaM
+65-672348247Yishun, SingaporeM
+81-3577990728Koto City, Tokyo, JapanM

带列的别名:以下查询用于创建列的别名 - name 和 City。

SELECT Name AS `Employee Name`, Age AS `Employee Age`, City 
FROM Employee; 

这将产生如下所示的结果:

Employee NameEmployee AgeCity
John25London
Marry24New York
Jo27Paris
Kim30Amsterdam
Ramesh28New Delhi
Huang28Beijing

具有聚合函数的别名:以下查询用于获取年龄大于 27 岁的员工数量。

SELECT COUNT(Name) AS `Number of Employees`
FROM Employee
WHERE Age > 27; 

这将带来以下结果:

Number of Employees
3

带表的别名:内部联接 Employee 和 Contact_Info表基于匹配列EmpID,语句如下。执行两个表的内连接时,会使用表的别名。

SELECT A.Name, A.Age, B.Address 
FROM Employee AS A
INNER JOIN Contact_Info AS B
ON A.EmpID = B.EmpID; 

上述查询的结果将是:

NameAgeAddress
Marry24Brooklyn, New York, USA
Jo27Grenelle, Paris, France
Kim30Geuzenveld, Amsterdam, Netherlands
Huang28Yizhuangzhen, Beijing, China