Ryan Ryan - 3 months ago 7
MySQL Question

Multiple joins in MySQL table

If I have one table that references the names of sponsors and the product ids of the products they recommend, as such:

--------------------------------
|Name |Product ID 1|Product ID 2|
--------------------------------
|Jon | 1 | 3 |
|Sally| 1 | 2 |
--------------------------------


And another table that lists the products:

----------------------------------------
|Product ID |Product Name|Product Price|
----------------------------------------
| 1 | Prod 1 | 25 |
| 2 | Prod 2 | 35 |
| 3 | Prod 3 | 45 |
----------------------------------------


How do I join these together so that I have the name of sponsor plus each product name and product price that they recommend?
INNER JOIN
and
LEFT JOIN
only seem to pull through one of the products, but not all of them.

Answer

Join twice.

SELECT s.name, p1.ProductName AS product_1_name, p1.ProductPrice AS product_1_price, p2.ProductName AS product_2_name, p2.ProductPrice AS product_2_price
FROM sponsers AS s
JOIN products AS p1 ON s.ProductID1 = p1.ProductID
JOIN products AS p2 ON s.ProductID2 = p2.ProductID
Comments