3

So, at the moment I have two columns in a table, one of which containing a JSON document, like so:

        CID:
        2
        Name:
        {"first" : "bob","1" : "william", "2" : "archebuster", "last" : "smith"}    

When I do a search on this column using:

  SELECT "CID", "Name"->>(json_object_keys("Name")) AS name FROM "Clients" WHERE 
  "Name"->>'first' LIKE 'bob' GROUP BY "CID";

I get:

  CID | name
--------------
  2   | bob
  2   | william
  2   | archebuster
  2   | smith

When really I want:

 CID | name
  2  | bob william archebuster smith

How would i go about doing this? I'm new to JSON in postgresql. I've tried string_agg and it wouldn't work, presumably because i'm working in a json column, despite the fact '->>' should type set the result to string

UPDATE:

enter image description here

4

1 回答 1

4

首先,您需要了解,如果您在SELECT子句中包含一个集合返回函数,您将创建一个隐含的.LATERAL CROSS JOIN

您在现实中的查询如下所示:

SELECT "CID", "Name"->>"key" AS name
FROM "Clients"
CROSS JOIN LATERAL json_object_keys("Name") AS "foo"("key")
WHERE "Name"->>'first' LIKE 'bob'
GROUP BY "CID", "Name"->>"key"

如果你真的想这样做,你可以在这里应用一个聚合函数(可能是array_aggor string_agg)。

SQLFiddle

于 2014-05-23T08:12:03.897 回答