I have four tables: families, parents, children, clubs. families have many parents and many children. The children have many clubs memberships.
I would like to create a "view" for fast searching names and email addresses that returns the each of the parents and children, names, email address, along with all an array of all the ids that of all the clubs that their children belong.
Here's what I have so far for the query I would like to be in the view:
SELECT
families.id AS family_id,
'Child' AS searchable_type,
concat(children.first_name, ' ',children.last_name) AS term,
'' AS email,
array_agg(memberships.club_id) AS clubs
FROM children
INNER JOIN families ON children.family_id = families.id
LEFT JOIN memberships ON children.id = memberships.child_id
GROUP BY families.id, term, email
UNION
SELECT
families.id AS family_id,
'Parent' AS searchable_type,
concat(parents.first_name, ' ',parents.last_name) AS term,
parents.email AS email,
array_agg(memberships.club_id) AS clubs
FROM parents
INNER JOIN families ON parents.family_id = families.id
INNER JOIN children ON families.id = children.family_id
LEFT JOIN memberships ON children.id = memberships.child_id
GROUP BY families.id, email, term
Question's are:
- How do I get rid of duplicate club_ids for children and parents?
It's a really slow query. If it is indexed, will the view be updated every time a write happens on child or parent?
Here is the execution plan: http://explain.depesz.com/s/BA9
- Here is a sqlfiddle: http://sqlfiddle.com/#!15/9c737/2