跳转至内容

MySQL/语言/别名

来自维基百科,面向开放世界的开放书籍

可以利用 AS 为表达式和列指定别名。别名用作表达式的列名称,并且可与 order by 或 having 子句一起使用。例如:

 SELECT 
     CONCAT(last_name,' ', first_name) AS full_name,
     nickname AS nick 
 FROM
     mytable 
 ORDER BY
     full_name

这些别名可以在 ORDER BY、GROUP BY 和 HAVING 子句中使用。它们不应用在 WHERE 子句中。

可以利用 AS 为表名称分配更短的名称以便引用。您可以省略 AS 这个词,并且仍然使用别名。例如:

 SELECT
     COUNT(B.Booking_ID), U.User_Location 
 FROM
     Users U
 LEFT OUTER JOIN
     Bookings AS B
 ON 
     U.User_ID    = B.Rep_ID AND
     B.Project_ID = '10'
 GROUP BY
     (U.User_Location)

别名在您使用自连接时起到了至关重要的作用。例如:人员表分别被称为 p 和 c 别名!

 SELECT
     p.name                                   AS parent,
     c.name                                   AS child,
     MIN((TO_DAYS(NOW())-TO_DAYS(c.dob))/365) AS minage
 FROM
     people AS p 
 LEFT JOIN
     people AS c 
 ON
     p.name=c.parent WHERE c.name IS NOT NULL
 GROUP BY
     parent HAVING minage > 50 ORDER BY p.dob;
华夏公益教科书