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

前端 未结 9 1650
我在风中等你
我在风中等你 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:03

    In the early days of SQL, it was chosen as the solution to the problem of how to deal with duplicate column names (see below note).

    To borrow a query from another answer:

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

    The column ProductID (and possibly others) is common to both tables and since the join condition syntax requires reference to both, the 'dot qualification' provides disambiguation.

    Of course, the better solution was to never have allowed duplicate column names in the first place! Happily, if you use the newer NATURAL JOIN syntax, the need for the range variables P and O goes away:

    SELECT ProductName, ProductRetailPrice, Quantity
      FROM Products NATURAL JOIN Orders
     WHERE OrderID = 123456
    

    But why is the AS keyword optional? My recollection from a personal discussion with a member of the SQL standard committee (either Joe Celko or Hugh Darwen) was that their recollection was that, at the time of defining the standard, one vendor's product (Microsoft's?) required its inclusion and another vendor's product (Oracle's?) required its omission, so the compromise chosen was to make it optional. I have no citation for this, you either believe me or not!


    In the early days of the relational model, the cross product (or theta-join or equi-join) of relations whose headings are not disjoint appeared to produce a relation with two attributes of the same name; Codd's solution to this problem in his relational calculus was the use of dot qualification, which was later emulated in SQL (it was later realised that so-called natural join was primitive without loss; that is, natural join can replace all theta-joins and even cross product.)

    Source: Business System 12, Notes keyed to slides of the presentation given at TTM Implementers’ Workshop, University of Northumbria, 2-3 June 2011 by Hugh Darwen

提交回复
热议问题