用左连接扇动记录

时间:2017-12-08 17:39:01

标签: sql postgresql

我遇到重复/扇出左连接。

表格Sales有多个品牌,但只有两个品牌名称不同,价格不同:BRAND 2

CSR Product也有两个BRAND 2品牌,但针对不同的州。

Product State Package没有两个BRAND 2

我正在brand字段加入这三个字段,但我看到每个BRAND 2我添加到一个表格中,它会增加大小。我怎样才能解决这个问题?

我需要所有Sales条记录,因此我还要加入Sales。这是我面临的第一个左连接 3020条记录所面临的较大问题的较小示例,第二条左连接是 450,000条记录

我的问题是:如果我LEFT JOIN获取所有销售记录,为什么在其他两个联合表中添加重复的BRAND 2会增加销售额记录?

销售:

brand   | pricing
----------------
BRAND 1    1
BRAND 2    2  <--- Brand 2
BRAND 2    7  <--- Brand 2
BRAND 3    3
BRAND 4    4
BRAND 5    5
BRAND 6    6

产品状态包:

brand   | state
----------------
BRAND 5    WA
BRAND 4    AZ
BRAND 2    MO
BRAND 1    VT
BRAND 8    SD

CSR产品:

brand   | state
----------------
BRAND 2    CT <--- Brand 2
BRAND 3    MA
BRAND 2    CA <--- Brand 2
BRAND 4    GA
BRAND 5    LA
BRAND 9    WA

查询:

SELECT s.brand, 
       tcp.brand as csr_brand, 
       tpsp.brand as psp_brand 
FROM   test_sales s 
       LEFT JOIN test_csr_product tcp 
              ON ( s.brand = tcp.brand ) 
       LEFT JOIN test_product_state_package tpsp 
              ON ( s.brand = tpsp.brand ); 

输出:

 -- Need all sales records
 sales_brand | csr_brand | psp_brand 
-------------+-----------+-----------
 BRAND 1     |           | BRAND 1
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 3     | BRAND 3   | 
 BRAND 4     | BRAND 4   | BRAND 4
 BRAND 5     | BRAND 5   | BRAND 5
 BRAND 6     |           | 
(9 rows)

BRAND 2中有三个Sales:您可以看到整个销售中sale_price有重复项:

sales_brand | sale_price | csr_brand | psp_brand 
-------------+------------+-----------+-----------
 BRAND 1     |          1 |           | BRAND 1
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 3     |          3 | BRAND 3   | 
 BRAND 4     |          4 | BRAND 4   | BRAND 4
 BRAND 5     |          5 | BRAND 5   | BRAND 5
 BRAND 6     |          6 |           | 
 (11 rows)

2 个答案:

答案 0 :(得分:0)

适合吗?

SELECT s.brand, 
       tcp.brand as csr_brand, 
       tpsp.brand as psp_brand 
FROM   (select distinct t.brand from test_sales t) s 
       LEFT JOIN test_csr_product tcp 
              ON ( s.brand = tcp.brand ) 
       LEFT JOIN test_product_state_package tpsp 
              ON ( s.brand = tpsp.brand ); 

答案 1 :(得分:0)

不确定如果我完全理解了你的问题,但如果你在结果中考虑tpsp.state,tcp.state,结果行就不会真正重复。