MySQL
  Home arrow MySQL arrow Page 5 - Using Subqueries In MySQL (part 2)
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Using Subqueries In MySQL (part 2)
By: RK Harigopal, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 14
    2003-07-31

    Table of Contents:
  • Using Subqueries In MySQL (part 2)
  • Total Recall
  • In And Out
  • A Solitary Existence
  • Turning The Tables
  • Show Me The Money
  • Adjusting For Inflation
  • A New Broom
  • Cleaning Up

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Using Subqueries In MySQL (part 2) - Turning The Tables


    (Page 5 of 9 )

    You can also use the results generated by a subquery as a table in the FROM clause of an enclosing SELECT statement. In order to illustrate, let's say I want to know the average number of services each branch office has. Therefore, the first thing I need to do is group the branches together and count the total number of services each one has,




    mysql> SELECT bid, COUNT(sid) AS stotal FROM branches_services GROUP BY
    mysql> bid;
    +------+--------+
    | bid | stotal |
    +------+--------+
    | 1011 | 4 |
    | 1012 | 1 |
    | 1013 | 1 |
    | 1031 | 3 |
    | 1032 | 1 |
    | 1033 | 1 |
    | 1041 | 2 |
    | 1042 | 2 |
    | 1101 | 1 |
    +------+--------+
    9 rows in set (0.17 sec)

    and then calculate the rounded-off average of the per-branch totals. Or, in a subquery,


    mysql> SELECT AVG(z.stotal) FROM (SELECT bid, COUNT(sid) AS stotal FROM
    branches_services GROUP BY bid) AS z;
    +---------------+
    | AVG(z.stotal) |
    +---------------+
    | 1.7778 |
    +---------------+
    1 row in set (0.21 sec)

    Thus, the table of results generated by the inner query is used in the FROM clause of the outer query. You can convert the average number above into an integer with the CEILING() function if you like.

    Note that when using subquery results in this manner, the result table generated by the inner query must be first aliased to a table name, or else MySQL will now know how to refer to columns within it. Look what happens when I re-run the query above without the table alias:


    mysql> SELECT AVG(stotal) FROM (SELECT bid, COUNT(bid) AS stotal FROM
    branches_services GROUP BY bid);
    ERROR 1246: Every derived table must have it's own alias

    Now, let's take it a step further. What if I need to list the branches where the number of services is above this average?


    mysql> SELECT bid FROM branches_services GROUP BY bid HAVING COUNT(sid)
    mysql> >
    1.7778;
    +------+
    | bid |
    +------+
    | 1011 |
    | 1031 |
    | 1041 |
    | 1042 |
    +------+
    4 rows in set (0.28 sec)

    To make it truly dynamic, you should combine the two queries above into the following complex query:


    mysql> SELECT bid FROM branches_services GROUP BY bid HAVING COUNT(sid)
    mysql> >
    (SELECT AVG(z.stotal) FROM (SELECT bid, COUNT(bid) AS stotal FROM branches_services GROUP BY bid) AS z);
    +------+
    | bid |
    +------+
    | 1011 |
    | 1031 |
    | 1041 |
    | 1042 |
    +------+
    4 rows in set (0.28 sec)

    Wanna make it really complicated? Add another query (and a join) around it to get the customer names corresponding to those branches.


    mysql> SELECT DISTINCT cname FROM clients, branches, (SELECT bid FROM
    branches_services GROUP BY bid HAVING COUNT(sid) > (SELECT AVG(z.stotal) FROM (SELECT bid, COUNT(bid) AS stotal FROM branches_services GROUP BY bid) AS z)) AS x WHERE clients.cid = branches.cid AND branches.bid = x.bid;
    +------------------+
    | cname |
    +------------------+
    | JV Real Estate |
    | DMW Trading |
    | Rabbit Foods Inc |
    +------------------+
    3 rows in set (0.33 sec)

    Whew!

    More MySQL Articles
    More By RK Harigopal, (c) Melonfire


     

       

    MYSQL ARTICLES

    - Take Some Load off MySQL with MemCached
    - MySQL Table Prefix Changer Tool in PHP
    - Using the SIGNAL Statement for Error Handling
    - Error Handling Examples
    - Error Handling
    - Completing a Search Engine with MySQL and PH...
    - Paginating Result Sets for a Search Engine B...
    - Building a Search Engine with MySQL and PHP 5
    - Using Boolean Operators for Full Text and Bo...
    - PHP, MySQL and the PEAR Database
    - Working with PHP and MySQL
    - Getting PHP to Talk to MySQL
    - Creating an RSS Reader: the Reader
    - MySQL Security Overview
    - Creating the Admin Script for a PHP/MySQL Bl...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway