是否有比在每一行中返回 "one" 值更有效的一对多关系的方法?

Is there a more efficient way to do a one-to-many relationship than having the "one" value in every row returned?

我有一个非常基本的一对多关系。有"nodes"个,每个节点关联多个"options"个。我正在做一个相当简单的连接,我的结果是这样的:

           content        | optionid |     content      
--------------------------+----------+------------------
 This is the node content |        1 | This is option 1
 This is the node content |        2 | This is option 2

但是,因为是一对多,所以每一行都有相同的节点内容:This is the node content。当我只需要一次时,return 每一行都具有相同的值似乎是多余的。有没有更好的方法?

好吧,这就是关系数据库的工作方式 - 你必须做出妥协。

如果您认为此查询在应用程序服务器和数据库之间生成的数据流太大,可以将其拆分为两个查询。单独加载 content 然后加载 options 避免冗余。这也可能具有性能优势(更少的内存、无 JOIN 等)。

另一方面,由于单独的查询 运行,这有延迟。特别是在循环查询中,这可能会非常慢。所以,一切都是为了妥协。

jsonb_object_agg aggregate function 似乎是个不错的选择。

SELECT
    n.content,
    jsonb_object_agg(o.optionid, o.content)
FROM node n
JOIN option o ON (
    -- what ever are the conditions
)
GROUP BY n.content;