与分层表的左连接会产生重复行

问题描述 投票:0回答:1

这个问题是建立在我问过的上一个问题的基础上的这里

我根据上述帖子中的答案(简化)得出了下表:

enter image description here

当我想要查询

wallet_balance_history
以及第一级父类别
category_id
引用
categories
表中的顶级父级时,这非常有效。我正在努力解决的是,如果我想查询较低级别的类别,我会得到同一
wallet_balance_history
行的重复行,因为该特定行中的
category_id
有多个子
category_id

这是一个简化的示例 - 表

Wallet_balance_history
:

身份证 类别_id
1 4
2 4

categories

身份证 parent_id 名字
4 x1
5 4 x1.1
6 4 x1.2

当我运行以下查询时:

select 
    wbh.id id, c1.name c1, c2.name c2, c3.name c3
from
    wallets_balance_history wbh 
left join 
    categories c1 on wbh.category_id = c1.id
left join 
    categories c2 on c2.parent_id = c1.id
left join 
    categories c3 on c3.parent_id = c2.id
where 
    wbh.id = 1;

我将得到以下结果集:

身份证 c1 c2
1 x1 x1.1
1 x1 x1.2

我想要实现的是对于每个

wallet_balance_history
行(ID 上唯一),最多应该有一个 c1、一个 2、一个 3。因此,当我查询交易时,我会得到如下内容:

身份证 c1 c2
1 x1 x1.1

我知道以目前的设计,我无法实现这一点。我知道查询无法知道孩子的

category_id

我想到了两个选择:

  1. wallets_balance_history.category_id
    中应该有最低的子级(从子级,我可以找到父级类别,但如果我有多个子级,则不一定相反)。问题是我不知道那里有什么类别级别。它是最低的,但它可能排名第三、第二,并且可能会造成其他复杂性。
  2. 采取创建一个桥接表的方式,其中每个
    wallet_balance_history.id
    都映射到一行或多行,具体取决于该事务中的类别/子类别数量。
sql oracle
1个回答
0
投票

要将每个 ID 的行数减少到 1,但仍然在 c2 和/或 c3 中显示多个类别,您可以使用

LISTAGG
GROUP BY
,如下所示:

SELECT
      wbh.id AS id
    , c1.name AS c1
    , LISTAGG(c2.name, ', ') WITHIN GROUP (ORDER BY c2.name) AS c2
    , LISTAGG(c3.name, ', ') WITHIN GROUP (ORDER BY c3.name) AS c3
FROM wallets_balance_history wbh
LEFT JOIN categories c1 ON wbh.category_id = c1.id
LEFT JOIN categories c2 ON c2.parent_id = c1.id
LEFT JOIN categories c3 ON c3.parent_id = c2.id
WHERE wbh.id = 1
GROUP BY
      wbh.id
    , c1.name

如果这不合适,请提供有关预期结果格式的更多详细信息。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.