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  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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 1)
By: RK Harigopal, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 11
    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:
      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 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

    - 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...
    - Building a Search Engine with MySQL and PHP 5
    - Using Boolean Operators for Full Text and Bo...
    - PHP, MySQL and the PEAR Database

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT