I'm pretty new to postgres and this is probably a novice question. How can I improve this query?
Three tables, campaigns 1-->M threads 1-->M messages. I have the campaign ID and I want all the threads with their total individual opens, clicks and replies counts of all the related messages where opens and clicks are in a JSONB field named extra under messages and replies are the messages that have column "direction"='received'.
select "threads".*,
count("messages"."extra"->'opens') as opens,
count("messages"."extra"->'clicks') as clicks,
(
select count("messages"."id")
from "messages"
where "messages"."thread_id" = "threads"."id"
and "messages"."direction"='received'
) as replies
from "threads"
inner join "messages"
on "messages"."thread_id" = "threads"."id"
where "threads"."campaign_id"
in ('campaign_uuid')
group by "threads"."id"