坚持附加名称到json中的子元素

时间:2018-04-30 18:44:11

标签: json postgresql

我有3个包含以下架构的表。

a.c1 int (pk),
a.c2 varchar(50),
a.c3 varchar(50),

b.c1 int(pk),
b.c2 int(fk) -> a.c1,
b.c3 varchar(50),
b.c4 varchar(50),

c.c1 int(pk),
c.c2 int(fk) -> b.c1,
c.c3 int(fk) -> a.c1,
c.c4 varchar(50),
c.c5 varchar(50)

我希望结果是

{
    "json_doc": {
        "a.c1": "val",
        "a.c2": "val",
        "a.c3": "val",
        "b": [{
            "b_c1_value": {
                "b.c1": "val",
                "b.c2": "val",
                "b.c3": "val",
                "b.c4": "val",
                "c": [{
                    "c_c1_value": {
                        "c.c1": "val",
                        "c.c2": "val",
                        "c.c3": "val",
                        "c.c4": "val",
                        "c.c5": "val"
                    }
                }]
            }
        }]
    }
}

有人可以帮助我使用正确的sql。我对Postgres非常陌生。

我已经走到了这一步:

select row_to_json(t)
        from (
                     select
                         *,
                         (
                             select array_to_json(array_agg(row_to_json(d)))
                             from (
                                            select
                                                *,
                                                (
                                                    select array_to_json(array_agg(row_to_json(dc)))
                                                    from (
                                                                 select  *
                                                                 from c
                                                                 where c.c2 = b.c1
                                                             ) dc
                                                ) as c

                                            from b
                                            where c2 = a.c1
                                        ) d
                         ) as b
                     from a
                        WHERE a.deployid = 19
                 ) t;

我需要填充数组的密钥名称。我坚持这个。非常感谢任何帮助!

0 个答案:

没有答案