2017-03-15 43 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

从产品....

这样,如果客户有订购产品不止一次,您只会得到一次结果