在获取数据时复制行

时间:2017-03-15 20:30:09

标签: sql postgresql

我有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 = 'ashutosh@gmail.com')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行?

2 个答案:

答案 0 :(得分: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 = 'ashutosh@gmail.com';  

答案 1 :(得分:0)

您可以通过向Select添加distinct来消除重复项 SELECT DISTINCT id_product,product_sku

FROM product ....

如果客户多次订购产品,您只能获得一次结果