SQL vs MySQL: Rules about aggregate operations and GROUP BY

前端 未结 4 1707
遥遥无期
遥遥无期 2021-02-14 05:11

In this book I\'m currently reading while following a course on databases, the following example of an illegal query using an aggregate operator is given:

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-14 05:45

    MySQL allows this non-standard SQL syntax because there is at least one specific case in which it makes the SQL nominally easier to write. That case is when you're joining two tables which have a PRIMARY / FOREIGN KEY relationship (whether enforced by the database or not) and you want an aggregate value from the FOREIGN KEY side and multiple columns from the PRIMARY KEY side.

    Consider a system with Customer and Orders tables. Imagine you want all the fields from the customer table along with the total of the Amount field from the Orders table. In standard SQL you would write:

     SELECT C.CustomerID, C.FirstName, C.LastName, C.Address, C.City, C.State, C.Zip, SUM(O.Amount)
        FROM Customer C INNER JOIN Orders O ON C.CustomerID = O.CustomerID
        GROUP BY C.CustomerID, C.FirstName, C.LastName, C.Address, C.City, C.State, C.Zip
    

    Notice the unwieldy GROUP BY clause, and imagine what it would look like if there were more columns you wanted from customer.

    In MySQL, you could write:

     SELECT C.CustomerID, C.FirstName, C.LastName, C.Address, C.City, C.State, C.Zip, SUM(O.Amount)
        FROM Customer C INNER JOIN Orders O ON C.CustomerID = O.CustomerID
        GROUP BY C.CustomerID
    

    or even (I think, I haven't tried it):

     SELECT C.*, SUM(O.Amount)
        FROM Customer C INNER JOIN Orders O ON C.CustomerID = O.CustomerID
        GROUP BY C.CustomerID
    

    Much easier to write. In this particular case it's safe as well, since you know that only one row from the Customer table will contribute to each group (assuming CustomerID is PRIMARY or UNIQUE KEY).

    Personally, I'm not a big fan of this exception to standard SQL syntax (since there are many cases where it's not safe to use this syntax and rely on getting values from any particular row in the group), but I can see where it makes certain kinds of queries easier and (in the case of my second MySQL example) possible.

提交回复
热议问题