简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM