简体   繁体   中英

How to return json formatted results for join query in postgres

I have this existing query:

SELECT to_json(table1) FROM table1

To return all of table in a nice json format. I need to add a join to this query, so my new query looks something like this:

SELECT (field1, field2, table2field1)
     FROM table1 INNER JOIN table2 ON field1 = table2id;

How can I get a similar style output in json format for this new query? to_json no longer works.

Previous overflow questions like this do not show how to return all rows.

you can try

WITH EXAMPLE (COL1,COL2,COL3) AS (
 SELECT field1, field2, table2field1
 FROM table1 INNER JOIN table2 ON field1 = table2id
)
SELECT TO_JSON(E) FROM EXAMPLE E;

Or without a CTE. Use your query w/o brackets round the select list in the from clause

select to_json(t) from (... your select query here ...) t;

ie

select to_json(t) from
(
 SELECT field1, field2, table2field1
 FROM table1
 INNER JOIN table2 ON field1 = table2id
) t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM