0

这是这个优秀问答的后续:13227142

我几乎必须做同样的事情(在 PostgreSQL 9.2 的约束下),但我只使用一张表。因此,查询使用了自连接(为了生成正确的 JSON 格式),这会导致重复的id字段。我怎样才能避免这种情况?

例子:

CREATE TABLE books
(
  id serial primary key,
  isbn text,
  author text,
  title text,
  edition text,
  teaser text
);

SELECT row_to_json(row)
FROM
(
  SELECT id AS bookid,
  author,
  cover
  FROM books
  INNER JOIN 
  (
    SELECT id, title, edition, teaser
    FROM books
  ) cover(id, title, edition, teaser)
  USING (id)
) row;

结果:

{
  "bookid": 1,
  "author": "Bjarne Stroustrup",
  "cover": {
    "id": 1,
    "title": "Design and Evolution of C++",
    "edition": "1st edition",
    "teaser": "This book focuses on the principles, processes and decisions made during the development of the C++ programming language"
  }
}

我想摆脱“封面”中的“id”。

4

3 回答 3

1

事实证明这是一项棘手的任务。据我所知,通过简单的查询是不可能实现的。一种解决方案是使用预定义的数据类型:

CREATE TYPE bookcovertype AS (title text, edition text, teaser text);

SELECT row_to_json(row)
FROM
(
  SELECT books.id AS bookid, books.author, 
    row_to_json(row(books.title, books.edition, books.teaser)::bookcovertype) as cover
  FROM books
) row;
于 2017-04-06T11:10:48.877 回答
1

你需要 id 才能加入,所以没有 id 你不能做这么短的查询。你需要构造它。喜欢:

select row_to_json(row,true)
FROM
(
with a as (select id,isbn,author,row_to_json((title,edition,teaser)) r from books
)
select a.id AS bookid,a.author, concat('{"title":',r->'f1',',"edition":',r->'f2',',"teaser":',r->'f3','}')::json as cover
  from a
) row;
                      row_to_json
--------------------------------------------------------
 {"bookid":1,                                          +
  "author":"\"b\"",                                    +
  "cover":{"title":"c","edition":"d","teaser":"\"b\""}}
(1 row)

同样没有加入,您使用的资源减少了两倍

于 2017-04-06T09:34:06.407 回答
0

为了完整起见,我自己偶然发现了另一个答案:字符串函数可以消除附加字段。但是,我更喜欢AlexM的答案,因为它会更快并且仍然与 PostgreSQL 9.2 兼容。

SELECT regexp_replace(
  (
      SELECT row_to_json(row)
      FROM
      (
        SELECT id AS bookid,
        author,
        cover
        FROM books
        INNER JOIN 
        (
          SELECT id, title, edition, teaser
          FROM books
        ) cover(id, title, edition, teaser)
        USING (id)
      ) row
  )::text,
  '"id":\d+,',
  '')
于 2017-04-06T11:25:13.227 回答