我有三个表,其中两个是常规数据表,另一个是多对多连接表。
这两个数据表:
table products
product_id | product_name | product_color
-----------------------------------------
1 | Pear | Green
2 | Apple | Red
3 | Banana | Yellow
而且
table shops
shop_id | shop_location
--------------------------
1 | Foo street
2 | Bar alley
3 | Fitz lane
我有一张包含商品ID
和商店ID
的交叉表:
table shops_products
shop_id | product_id
--------------------
1 | 1
1 | 2
2 | 1
2 | 2
2 | 3
3 | 2
3 | 3
我想从店铺ID为3的店铺中选择商品数据。我尝试了这里很多带有连接、左连接和内连接的示例,但我不知道自己在做什么,也不知道哪里出了问题。我的查询语句会返回所有商品,而不管它们是否在指定的店铺中:
SELECT products.product_name, products.product_color
FROM products
LEFT OUTER JOIN shops_products
ON products.product_id = shops_products.product_id
AND shops_products.shop_id = 3
LEFT OUTER JOIN shops
ON shops_products.shop_id = shops.shop_id
期望的输出如下:
product_name | product_color
----------------------------
Apple | Red
Banana | Yellow
这是在MySQL中,感谢任何帮助,我非常感激。