2015-10-28 85 views
5

我有三個表,其中2個是常規數據表,1個是多對多聯結表。具有多對多關係的聯結表上的SQL連接

兩個數據表:

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 

我有一個包含了shop_id的和product_id的結合表:

table shops_products 

shop_id | product_id 
-------------------- 
1   | 1 
1   | 2 
2   | 1 
2   | 2 
2   | 3 
3   | 2 
3   | 3 

我想從店鋪shop_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的,謝謝任何幫助,我真的很感激它。

回答

15

我喜歡從外部開始在移動 所以,想象一下所有列在短短的一個表中所有被卡在一起,你可以寫這樣的:。

SELECT * 
FROM products 
WHERE shop_id = 3 

你那麼只需要添加連接就可以使這個語句成爲可能。我們知道我們需要接下來添加連接表(因爲它是直接連接到產品表的,因爲它具有product_id)。因此,加入是下一步:

SELECT products.* 
FROM products 
INNER JOIN shops_products 
ON products.product_id = shops_products.product_id 
WHERE shops_products.shop_id = 3 

實際上你可以在這裏停止...因爲shop_id已經存在於連接表上。但是,讓我們說你也想在最後一列的商店名稱,然後添加商店表加入。

SELECT products.*, shops.shop_name 
FROM products 
INNER JOIN shops_products 
ON products.product_id = shops_products.product_id 
INNER JOIN shops 
ON shops_products.shop_id = shops.shop_id 
WHERE shops_products.shop_id = 3 
+1

真是個好的答案! –

+0

謝謝!這解決了我的問題,並幫助我理解解決方案。再次感謝,我會在5分鐘內接受它,當它讓我:) –

1

你可以試試這個。

SELECT products.product_name, products.product_color 
FROM products 
INNER JOIN shops_products 
ON products.product_id = shops_products.product_id 
WHERE shops_products.shop_id = 3 
0
SELECT aa.product_id, aa.product_name, aa.product_color 
FROM products AS aa 
INNER JOIN shops_products AS bb 
ON aa.product_id = bb.procuct_id 
WHERE bb.shop_id = 3; 
相關問題