tags:

views:

46

answers:

2

I have 3 MySQL tables.

companies with company_id and company_name

products with product_id and company_id

names with product_id, product_name and other info about the product

I'm trying to output the product_name and the company_name in one query for a given product_id.

Basically I need information from the names and companies tables and the link between them is the products table.

How do I do a join that needs to "bounce" off a third table?

Something like this but this obviously doesn't work:

SELECT product_name, company_name
FROM names
LEFT OUTER JOIN companies ON 
    (names.product_id = products.product_id and products.company_id = companies.company_id)
WHERE product_id = '12345'
+2  A: 
select n.product_name, c.company_name 
from names n
left outer join products p on n.product_id = p.product_id
left outer join companies c on p.company_id = c.company_id
where n.product_id = '12345' 
RedFilter
+1 Heh - beat me by 25 seconds.
Mark Byers
Well this was easy. I learned something new!
Enkay
+1  A: 

You nearly have it, you just need to include the third table as another join in your query:

SELECT product_name, company_name
FROM names
LEFT JOIN products ON names.product_id = products.product_id
LEFT JOIN companies ON products.company_id = companies.company_id
WHERE product_id = '12345'

Also you should note that if you are using LEFT JOIN then the company name could be NULL if the company that made the product is unknown. So you need to test for that in your code to avoid an exception. If you know that it should never be NULL, or if you want to explicilty exclude products for which you don't know the company then use an INNER JOIN instead of a LEFT JOIN in both cases.

Mark Byers
Thank you very much! It was much easier than all the things I tried! As for the company name, it is always known. The system doesn't allow null company names.
Enkay
@Enkay: I think you may have missed the point. It's not about whether the column company_name is nullable or not, but that the row in the products table that joins the product_id to the company_id could be missing, which would cause the company_name to be NULL even if that column is not nullable. You should try to understand the difference between INNER JOIN and OUTER JOIN and ensure that you are using the correct one.
Mark Byers
You're right I didn't get what you were saying at first. I think in this case I should indeed be using an INNER join. I'm just starting to understand more complex mysql statements. Thank you.
Enkay