13.6. Using Subqueries in the FROM Clause


13.6. Using Subqueries in the FROM Clause

Subqueries may be used in the FROM clause of a SELECT statement. In the following query, we find the average of the sums of the population of each continent:

 mysql> SELECT AVG(cont_sum)     -> FROM (SELECT Continent, SUM(Population) AS cont_sum     ->       FROM Country     ->       GROUP BY Continent     ->      ) AS t; +----------------+ | AVG(cont_sum)  | +----------------+ | 868392778.5714 | +----------------+ 

Every table that appears in a FROM clause must have a name, so a subquery in the FROM clause must be followed by a table alias.

The SELECT in the FROM clause can be a table subquery, even if not all of its values are used by the outer query. This is shown by the preceding example, where the Continent column selected by the subquery is not used by the outer query.

Subqueries in FROM clauses cannot be correlated with the outer statement.



MySQL 5 Certification Study Guide
MySQL 5.0 Certification Study Guide
ISBN: 0672328127
EAN: 2147483647
Year: 2006
Pages: 312

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net