通过映射表连接 - 重复值

时间:2018-02-04 03:00:00

标签: sql postgresql

我有三张桌子,想要获得每种产品的包装细节。所以我left join productpacks通过productproduct.pack(FK) == productpacks.product_pack

然后我仍然需要包的详细信息,因此我根据productpacks.official_pack匹配product.pack == productpacks.product_pack加入packs.pack并获取volumeweight

     product         productpacks           packs
     -------         ------                 ----------
     name            product_pack           pack (PK)          
     pack (FK)       official_pack          info1
     customer        customer               info2

虽然使用product,但这似乎正在返回LEFT JOIN的重复项。如何通过诸如productpacks

之类的通过表加入另一个表格

产品

product   |    pack    |    customer     |   time
--------------------------------------------------
product1       16oz         customer1       1:00
product1       16oz         customer1       2:00
product3       11oz         customer1       3:00
product4       16 OZ        customer2       4:00

ProductPacks

product_Pack   |    official_Pack      |  customer
--------------------------------------------------
16oz                Sixteen OZ            customer1
12oz                Twelve OZ             customer1
11oz                Eleven OZ             customer1
16 OZ               SIXTEEN OZ            customer2

pack           |   info1   |   info2
-----------------------------------
Sixteen OZ          12          Red
Twelve OZ           13          Blue
Eleven OZ           14          Green
SIXTEEN OZ          16          etc..

预期输出:

product   |    pack    |    customer  |  time  |   pack       | info1 | info2
-------------------------------------------------------------------------------
product1       16oz         customer1    1:00      Sixteen OZ    12     Red

实际输出:

product   |    pack    |    customer  |  time  |   product_pack  | official_pack | customer | pack       | info1 | info2
-------------------------------------------------------------------------------
product1       16oz         customer1    1:00    16oz           Sixteen OZ   customer1    Sixteen OZ    12     Red
product1       16oz         customer1    1:00    16oz           Sixteen OZ   customer1    Sixteen OZ    12     Red

SQL

SELECT * FROM product p
LEFT JOIN productpacks pp 
  ON p.customer = pp.customer
  AND p.pack = pp.product_pack
LEFT JOIN packs pk
  ON pp.official_pack = pk.pack

3 个答案:

答案 0 :(得分:0)

@Growler你的结果中有重复项,因为你的产品表中有重复项(至少在你的例子中)。

答案 1 :(得分:0)

在表产品中,因为product1的时间是1:00和2:00,您的查询返回正确的答案,即2个不同的行,因为时间列差异是正确的。我认为您发布的结果包含时间1:00和2:00,而不是1:00和1:00

答案 2 :(得分:0)

您错过了group by子句,请检查以下查询一次:

SELECT p.product,p.pack,c.customer,p.time,pk.pack,pk.info1,pk.info2 
FROM product p
LEFT JOIN productpacks pp 
  ON p.customer = pp.customer
  AND p.pack = pp.product_pack
LEFT JOIN packs pk
  ON pp.official_pack = pk.pack
GROUP BY p.product,p.pack,c.customer,p.time,pk.pack,pk.info1,pk.info2 ;