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  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
MYSQL

Using Subqueries In MySQL (part 2)
By: RK Harigopal, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 16
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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

    - MySQL Security Tips
    - Designing a MySQL Database: Tips and Techniq...
    - The Three Most Important MySQL Queries
    - Null and Empty Strings
    - MySQL Server Tuning Tips and Tricks
    - MySQL Query Optimizations and Schema Design
    - MySQL Benchmarking Tools and Utilities
    - MySQL Benchmarking Concepts and Strategies
    - 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...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek