【发布时间】:2017-12-08 17:39:00
【问题描述】:
我遇到重复/扇出左连接的问题。
表Sales有多个品牌,但只有两个相同的品牌名称不同的定价:BRAND 2。
表CSR Product也有两个BRAND 2品牌,但是针对不同的状态。
表Product State Package 没有两个BRAND 2。
我在brand 字段上加入这三个,但我看到每个BRAND 2 添加到表中,它会成倍增加大小。我怎样才能解决这个问题?
我需要所有 Sales 记录,因此我离开了销售部门。这是我面临的一个较大问题的较小示例,第一个左连接是 3020 条记录,第二个左连接是 450,000 条记录。
我的问题是:如果我是 LEFT JOINing 来获取所有销售记录,为什么将重复的 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
企业社会责任产品:
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)
在Sales 中有三个BRAND 2:您可以看到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)
【问题讨论】:
-
你能写出你想要输出的例子吗?
标签: sql postgresql