Performing SELECT Statements that Use More than Two Tables


Joins can be used to connect any number of tables. You can use the following formula to calculate the number of joins you will need in your WHERE clause:

Add all the number of tables used in your query, and then subtract 1 from this total.

In the example shown in the previous section, there were two tables used in the query: products and product_types . Therefore, the number of joins required is 1 (=2 - 1), and indeed only one join is used in that example.

Let s consider a more complicated example that will involve four tables and will therefore require three joins. Let s say you want to see the following information:

  • The purchases each customer has made

  • The customer s first and last name

  • The name of the product they purchased

  • The name of the product type

In order to view this information, you need to query the customers , purchases , products , and product_types tables, and your joins will need to navigate the foreign key relationships between these tables. The following list shows the required navigation:

  1. To get the customer who made the purchase, you join the customers and purchases tables using the customer_id columns from those respective tables.

  2. To get the product purchased, you join the products and purchases tables using the product_id columns from those respective tables.

  3. To get the product type name for the product, you join the products and product_types tables using the product_type_id columns from those respective tables.

Using this navigation, your query may appear as follows (notice the aliases and joins used in this query):

 SELECT c.first_name, c.last_name, p.name AS PRODUCT, pt.name AS TYPE FROM customers c, purchases pr, products p, product_types pt WHERE c.customer_id = pr.customer_id AND p.product_id = pr.product_id AND p.product_type_id = pt.product_type_id; 

Notice that I ve also renamed the heading for the product name to PRODUCT , and renamed the product type name to TYPE . The output of this query is as follows:

 FIRST_NAME LAST_NAME PRODUCT      TYPE ---------- ---------- ------------------------------ ---------- John  Brown   Modern Science     Book Cynthia  Green  Modern Science      Book Steve  White  Modern Science      Book Gail  Black  Modern Science    Book John  Brown  Chemistry      Book Cynthia Green   Chemistry      Book Steve  White  Chemistry      Book Gail   Black  Chemistry        Book Steve  White Supernova     Video 

The two examples you ve seen so far use the equality operator (=) in the joins, and because of this, these joins are known as equijoins . As you ll see in the next section, the equijoin is not the only join you can use.




Oracle Database 10g SQL
Oracle Database 10g SQL (Osborne ORACLE Press Series)
ISBN: 0072229810
EAN: 2147483647
Year: 2004
Pages: 217

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