返回JSON作为关联对象?

时间:2018-12-23 00:10:04

标签: postgresql

我正在使用Postgres 11,并具有以下SQL:

SELECT json_agg("Result"."record")
FROM (SELECT jsonb_build_object('emailAddress', "User"."emailAddress", 'displayName', "User"."displayName") as "record"
      FROM "User")
"Result"

,它会返回一行,如下所示:

[
  {"displayName": "Keith Stephens", "emailAddress": "kstephensqv@goo.gl"},
  {"displayName": "Robert Armstrong", "emailAddress": "rarmstrongrf@gooogle.es"}, 
  {"displayName": "Aaron Wagner", "emailAddress": "awagnerrh@cambo.ac.uk"}
]

我想要的是作为关联对象的结果:

{
  "kstephensqv@goo.gl": {"displayName": "Keith Stephens", "emailAddress": "kstephensqv@goo.gl"},
  "rarmstrongrf@gooogle.es": {"displayName": "Robert Armstrong", "emailAddress": "rarmstrongrf@gooogle.es"}, 
  "awagnerrh@cambo.ac.uk": {"displayName": "Aaron Wagner", "emailAddress": "awagnerrh@cambo.ac.uk"}
}

有什么方法可以仅使用Postgres SQL表达式来获得所需的结果吗?

1 个答案:

答案 0 :(得分:0)

因此,在发布了这个问题之后,我立即想到了一个想法,并提出了我想做的事情:

SELECT json_object_agg("Result"."key", "Result"."record")
FROM (SELECT "User"."emailAddress" as "key", jsonb_build_object('emailAddress', "User"."emailAddress", 'displayName', "User"."displayName") as "record"
      FROM "User") "Result"