Multiple joins in MySQL table

て烟熏妆下的殇ゞ 提交于 2019-12-20 04:15:42

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/39276349/multiple-joins-in-mysql-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!