Search code examples
arraysjsonpostgresqlaggregate-functionspostgresql-9.5

How to do exactly same thing as array_to_json(array_agg(tags.*)) for N columns


I am currently using PostgreSQL JSON capabilities to create JSON objects out of my query so I can easily use it on my application or pass it to the frontend.

array_to_json(array_agg(tags.*)) does exactly when I need to (creates JSON objects with columns as a keys from the data and convert it into array), however I haven't found any way how to do the same if I need only one or two columns from tags. I played with various JSON and array functions but I've never achieved the same result. Thanks for help

Whole query

SELECT
    tags_components.component_id,
    array_to_json(array_agg(tags.*)) as tags
FROM tags_components 
LEFT JOIN tags ON tags.id = tags_components.tag_id 
AND tags_components.component_name = 'company'
GROUP BY tags_components.component_id

Solution

  • Use a derived table, e.g.:

    SELECT
        tags_components.component_id,
        array_to_json(array_agg(tags.*)) as tags
    FROM tags_components 
    LEFT JOIN (
        SELECT id, name -- only two columns
        FROM tags 
        ) tags
    ON tags.id = tags_components.tag_id 
    AND tags_components.component_name = 'company'
    GROUP BY tags_components.component_id