AS命令用于使用别名重命名列或表。
别名仅在查询期间存在。
下面的SQL语句创建两个别名,一个用于CustomerID列,另一个用于CustomerName列:
SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;
以下SQL语句创建两个别名。请注意,如果别名名称包含空格,则需要双引号或方括号:
SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers;
下面的SQL语句创建一个名为“Address”的别名,该别名结合了四列(Address, PostalCode, City 和 Country):
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address FROM Customers;
注意:要使上述SQL语句在MySQL中运行,请使用以下命令:
SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address FROM Customers;
下面的SQL语句选择CustomerID = 4的所有客户订单。我们使用“ Customers”和“ Orders”表,并分别为其赋予表别名“ c”和“ o”(此处使用别名使SQL更短):
SELECT o.OrderID, o.OrderDate, c.CustomerName FROM Customers AS c, Orders AS o WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID;