What's the purpose of SQL keyword “AS”?

前端 未结 9 1646
我在风中等你
我在风中等你 2020-11-30 20:37

You can set table aliases in SQL typing the identifier right after the table name.

SELECT * FROM table t1;

You can even use the keyword

9条回答
  •  孤城傲影
    2020-11-30 21:02

    Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.

    Example 1

    SELECT P.ProductName,
           P.ProductGroup,
           P.ProductRetailPrice
    FROM   Products AS P
    

    Example 2

    SELECT P.ProductName,
           P.ProductRetailPrice,
           O.Quantity
    FROM   Products AS P
    LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
    WHERE  O.OrderID = 123456
    

    Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).

    SELECT P.ProductName,
           P.ProductRetailPrice,
           O.Quantity
    FROM   Products P
    LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
    WHERE  O.OrderID = 123456
    

    As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.

    Example 4

    SELECT P.ProductName AS "Product",
           P.ProductRetailPrice AS "Retail Price",
           O.Quantity AS "Quantity Ordered"
    FROM   Products P
    LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
    WHERE  O.OrderID = 123456
    

    Output of Example 4

    Product             Retail Price     Quantity Ordered
    Blue Raspberry Gum  $10 pk/$50 Case  2 Cases
    Twizzler            $5 pk/$25 Case   10 Cases
    

提交回复
热议问题