MySQL
  Home arrow MySQL arrow Page 4 - Using Subqueries In MySQL (part 1)
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 1)
By: RK Harigopal, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2003-07-24


    Table of Contents:
  • Using Subqueries In MySQL (part 1)
  • Sub-Zero Code
  • Turning The Tables
  • Back To Basics
  • Branching Out
  • Having Your Code, And Eating It Too
  • Apples And Oranges

  • 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 1) - Back To Basics
    ( Page 4 of 7 )

    You already know that you can obtain a complete list of all the records in a table with a simple SELECT * - for example, a list of all clients:


    mysql> SELECT * FROM clients;
    +-----+-----------------------------+
    | cid | cname |
    +-----+-----------------------------+
    | 101 | JV Real Estate |
    | 102 | ABC Talent Agency |
    | 103 | DMW Trading |
    | 104 | Rabbit Foods Inc |
    | 110 | Sharp Eyes Detective Agency |
    +-----+-----------------------------+
    5 rows in set (0.22 sec)

    You can also attach a join and a WHERE clause to the SELECT statement in order to filter the list of records down to only those matching specific criteria - for example, a list of all clients with branch offices in California only:


    mysql> SELECT cname, bdesc, bloc FROM clients, branches WHERE
    mysql> clients.cid =
    branches.cid AND branches.bloc = 'CA';
    +-----------------------------+----------------------+------+
    | cname | bdesc | bloc |
    +-----------------------------+----------------------+------+
    | JV Real Estate | Corporate HQ | CA |
    | Rabbit Foods Inc | Branch Office (West) | CA |
    | Sharp Eyes Detective Agency | Head Office | CA |
    +-----------------------------+----------------------+------+
    3 rows in set (0.00 sec)

    How about something a little more involved? Let's say I need a list of all the branch offices belonging to "Rabbit Foods Inc". Now, I could do this by running two SELECT queries, one after another, to first get the customer ID of "Rabbit Foods Inc", and then using that ID (104) in another query to get the list of branch offices linked to that customer,


    mysql> SELECT cid FROM clients WHERE cname = 'Rabbit Foods Inc';
    +-----+
    | cid |
    +-----+
    | 104 |
    +-----+
    1 row in set (0.17 sec)

    mysql> SELECT bdesc FROM branches WHERE cid = 104;
    +----------------------+
    | bdesc |
    +----------------------+
    | Branch Office (East) |
    | Branch Office (West) |
    +----------------------+
    2 rows in set (0.17 sec)

    by equi-joining the "clients" and "branches" tables,


    mysql> SELECT bdesc FROM branches, clients WHERE clients.cid =
    mysql> branches.cid
    AND clients.cname = 'Rabbit Foods Inc';
    +----------------------+
    | bdesc |
    +----------------------+
    | Branch Office (East) |
    | Branch Office (West) |
    +----------------------+
    2 rows in set (0.22 sec)

    or with a subquery.


    mysql> SELECT bdesc FROM branches WHERE cid = (SELECT cid FROM clients
    WHERE cname = 'Rabbit Foods Inc');
    +----------------------+
    | bdesc |
    +----------------------+
    | Branch Office (East) |
    | Branch Office (West) |
    +----------------------+
    2 rows in set (0.22 sec)

    Thus, a subquery makes it possible to combine two or more queries into a single statement, and use the results of one query in the conditional clause of the other. Subqueries are usually regular SELECT statements, and are separated from their parent query by parentheses, as in the example above.

    A subquery must return a single column of results, or else MySQL will not know how to handle the result set. Consider the following example, which demonstrates by having the subquery return a two-column result set:


    mysql> SELECT bdesc FROM branches WHERE cid = (SELECT cid, cname FROM
    clients WHERE cname = 'Rabbit Foods Inc');
    ERROR 1239: Cardinality error (more/less than 1 columns)

    You can nest subqueries to any depth, so long as the basic rules above are followed. Consider the following example, which demonstrates by listing the services used by Sharp Eyes Detective Agency:


    mysql> SELECT sname FROM services WHERE sid = (SELECT sid FROM
    branches_services WHERE bid = (SELECT bid FROM branches WHERE cid = (SELECT cid FROM clients WHERE cname = 'Sharp Eyes Detective Agency')));
    +------------+
    | sname |
    +------------+
    | Accounting |
    +------------+
    1 row in set (0.28 sec)



     
     
    >>> 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 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek