I'm trying to write a fairly straightforward PSQL query to retrieve some data (I realise it's not the most efficient query right now):
SELECT c.name AS article, c.id AS article_id, t.name AS template, t.id AS template_id, brand_names, COUNT(p.component_id)
FROM publications p
INNER JOIN components c
(SELECT string_agg(b.name, ', ') AS brand_names
FROM brands b
INNER JOIN brands_components
ON b.id = brands_components.brand_id
WHERE brands_components.component_id = c.id
) brand_query
ON c.id = p.component_id
INNER JOIN brands_components bc
ON c.id = bc.component_id
AND bc.brand_id IN (16, 23, 24, 35, 37)
INNER JOIN components_templates ct
ON c.id = ct.component_id
INNER JOIN templates t
ON t.id = ct.template_id
This gives me a syntax error though on line 4. What's missing? If I run the subquery alone it works fine:
syntax error at or near "SELECT" LINE 4: (SELECT string_agg(b.name, ', ') AS brand_names ^ : SELECT c.name AS article, c.id AS article_id, t.name AS template, t.id AS template_id, brand_nam
The subquery is designed to retrieve all the brand names per component and display them in a single row instead of many. Their join table is brands_components.
A fiddle that is available here, the desired result should be something like:
article article_id template template_id count brands
--------------------------------------------------------------------------------------------------------------
component one | 1 | template one | 1 | 4 | brand one, brand two, brand three, brand four
JOIN something alias...? Typically it's the keyword "ON"