2017-03-15 37 views
0

我有3個表中的數據:產品,訂閱和客戶重複行而獲取

SELECT id_product, product_sku 

FROM product 

JOIN (select fk_product_subscribed, fk_customer from subscription 

      where subscription.status = 'active')S 

    ON S.fk_product_subscribed = product.id_product 

JOIN (select id_customer from customer 

      where email = '[email protected]')C 

    ON C.id_customer = S.fk_customer; 

這我得到的結果是:

+ ---------- + ----------------------- + 
| id_product | product_sku    | 
+ ---------- + ----------------------- + 
| 100  | veggie for 3 happy meal | 
| 100  | veggie for 3 happy meal | 
+ ---------- + ----------------------- + 

爲什麼我得到2行,而不是一個?

回答

1

原因有多個匹配存在,而你JOIN。在這種情況下,您可以使用distinct來代替SELECT distinct id_product, product_sku。而且,在你的子查詢中沒有看到列選擇的原因。你可以在那裏直接加入。

您的查詢可以像

SELECT distinct id_product, product_sku 

FROM product p 

JOIN subscription s 

    ON s.fk_product_subscribed = p.id_product 

JOIN customer c ON c.id_customer = s.fk_customer 

where s.status = 'active' 
and c.email = '[email protected]'; 
+0

我也是這樣做的, SELECT id_product,pr oduct_sku 從產品 JOIN訂閱 ON subscription.fk_product_subscribed = product.id_product JOIN客戶 ON customer.id_customer = subscription.fk_customer WHERE customer.email = '[email protected]' 和subscription.status = '主動' ; 仍然相同的結果 – Rock

+0

@ashutoshsingh,請參閱編輯如果有幫助的答案。 – Rahul

+0

對不同的我甚至從我的查詢中得到正確的結果。我需要明白爲什麼沒有明顯的我在那裏得到兩行。我很新這裏 – Rock

0

您可以通過添加不同的選擇 SELECT DISTINCT id_product消除重複,product_sku

從產品....

這樣,如果客戶有訂購產品不止一次,您只會得到一次結果