AS命令用于使用別名重命名列或表。
別名僅在查詢期間存在。
下面的SQL語句創(chuàng)建兩個(gè)別名,一個(gè)用于CustomerID列,另一個(gè)用于CustomerName列:
SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;
以下SQL語句創(chuàng)建兩個(gè)別名。請(qǐng)注意,如果別名名稱包含空格,則需要雙引號(hào)或方括號(hào):
SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers;
下面的SQL語句創(chuàng)建一個(gè)名為“Address”的別名,該別名結(jié)合了四列(Address, PostalCode, City 和 Country):
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address FROM Customers;
注意:要使上述SQL語句在MySQL中運(yùn)行,請(qǐng)使用以下命令:
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;