I have the following example data structure of customer that can be part of multiple groups using a junction table:
customer
---
ID int primary key
group
---
ID int primary key
customer_to_group_junction
---
group_id int FK
customer_id int FK
id int primary key
I need to get customers that have specific groups they are part of, and I need to get a list of all customers that are part of at least 1 group in multiple lists of group. For example I want to get all customers that are in group [5 OR 6] AND [1 OR 3]
, so for example a customer in group 5 and 1 wold be a returned, but somebody in 1 and 7 or just 1 not. Just doing WHERE group_id IN (5,6) AND group_id IN (1,3)
does not seem to work, so I am looking for alternative.
I got this so far:
FROM customer c
INNER JOIN customer_to_group_junction at1 ON c.id = at1.customer_id
INNER JOIN customer_to_group_junction at2 ON c.id = at2.customer_id
WHERE at1.group_id IN (5, 6)
AND at2.group_id IN (1, 3);
I wonder if there is a better way to do it that is more performant. Thanks