Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

multiple joins in a cfquery

Status
Not open for further replies.

PushCode

Programmer
Dec 17, 2003
573
US
Can someone steer me in the right direction with this query? I'm trying to select any product from the product table who's product_id matches any product_id's from the other three tables.

What i have doen't work. Any ideas?

<cfquery name="get_prod_by_catmatocc" datasource="#ds#">
SELECT a.product_id, a.title, a.price, a.img_thumb
FROM products a, product_materials_matrix b, product_sub_categories c,
product_category_matrix d
WHERE a.product_id = b.product_id
AND a.product_id = c.product_id
AND a.product_id = d.product_id
AND b.material_id = #url.matid#
AND c.sub_category_id = #url.occid#
AND d.category_id = #url.catid#
</cfquery>
 
Code:
select a.product_id
     , a.title
     , a.price
     , a.img_thumb
  from products a
 where exists
     ( select * 
         from product_materials_matrix 
        where product_id = a.product_id 
          and material_id = #url.matid# )
    or exists
     ( select *
         from product_sub_categories 
        where product_id = a.product_id 
          and sub_category_id = #url.occid# )
    or exists
     ( select *
         from product_category_matrix 
        where product_id = a.product_id      
          and category_id = #url.catid# )
be careful with sql injection from your url strings

rudy | r937.com | Ask the Expert | Premium SQL Articles
SQL for Database-Driven Web Sites (next course starts July 10 2005)
 
r937,

Your query actually seem to return every item in the products table, as opposed to returning only select items. Any idea why this may be?
 
probably because all the products have at least one related row in one of the three tables

you said "matches any product_id's from the other three tables"

as you can see, i interpreted this as a combination of OR conditions

perhaps you meant AND?


rudy | r937.com | Ask the Expert | Premium SQL Articles
SQL for Database-Driven Web Sites (next course starts July 10 2005)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top