I have have a query that returns rows from a blog database that can match a number of different supplied criteria. The query works as expected to return the data I require.
A typical example of the sql:
, c.name as category_name
, ts_headline(ts.title, ts.ts_query) as headline
, ts.rank from (
, ts_rank_cd(search_tsv, ts_query) AS rank
from public.posts, plainto_tsquery('this is a test post') as ts_query
where search_tsv @@ ts_query order by rank desc ) as ts
join public.category_relationships as cr
on cr.post_id = ts.post_id
join public.categories as c
on cr.category_id = c.category_id
join public.posts as p
on cr.post_id = p.post_id
where cr.category_id = 9
p.added between '2010-12-01 00:00:00' and '2010-12-31 23:59:59'
p.post_id in (
where tag = 'tag1' or tag = 'tag2' or tag = 'tag3')
order by ts.rank, p.added DESC
While I can search for a blog post using the above based on tags as part of the search criteria, I do not include the tags in the returned data since I will get a row of data for a certain post_id for each tag that exists for that post_id.
What I would like to do is include the following as a subquery for returning a formatted string containing the tags for the relevant post:
select tag from public.tags where post_id = p.post_id
), ', ')
Of course, the error is obvious: the alias 'p' does not exist in the subquery scope. My dilemma is how do I incorporate this subquery into the larger query above and pull the p.post_id into the subquery? I'm sure I'm just being obtuse here, but any thoughts would be appreciated