I have a table like this:
CREATE TABLE preferences (name varchar, preferences varchar[]);
INSERT INTO preferences (name, preferences)
VALUES
('John','{pizza, spaghetti}'),
('Charlie','{spaghetti, rice}'),
('Lucy','{rice, potatoes}'),
('Beth','{bread, cheese}'),
('Trudy','{rice, milk}');
So from the table
John {pizza, spaghetti}
Charlie {spaghetti, rice}
Lucy {rice, potatoes}
Beth {bread, cheese}
Trudy {rice, milk}
I would like group all rows that have elements in common (even if it is through other people). So in this case I would like to end up with:
{John,Charlie,Lucy,Trudy} {pizza,spaghetti,rice,potatoes,milk}
{Beth} {bread, cheese}
because Johns preferences intersect with those of Charlie, and those of Charlie intersect with those of Lucy and with those of Trudy.
I already haven an array_intersection function like this:
CREATE OR REPLACE FUNCTION array_intersection(anyarray, anyarray)
RETURNS anyarray
language sql
as $FUNCTION$
SELECT ARRAY(
SELECT UNNEST($1)
INTERSECT
SELECT UNNEST($2)
);
$FUNCTION$;
and know the array_agg function to aggregate arrays, but how to turn those into a grouping like I want is the step I am missing.
array_intersects, because you can't use&&operator?.. how is it different?..