Join MySQL tables in ruby on rails 2.3.3 only if all rows from one table are in another table

55 Views Asked by At

I need to select all rows from table Client where Service has all certificates the Client needs.

Client
client_id

Service
service_id

Certificate
certificate_id

ClienCertificate
client_id / certificate_id
1           2 
2           3
3           2
3           3

ServiceCertificate
service_id / certificate_id
1           2 
1           3
2           2
3           4

If I'm service with id = 1 I should see all 3 clients since I have all the certificates they ask for. If I'm service with id = 2 I should see only client 2 (not client 3 since I'm missing certificate 3), and if I'm service with id = 3 I would see an empty response.

This is what I have so far

@clients = Client.all()
.joins(:client_certificates)
.joins(:service_certificates)
.order(:created_at)
.group("client_id");

But of course, this selects all clients even if the service only has 1 of all the certificates the clients is asking for. How could I only select when the service has all the certificates the client wants (service can have more certificates that the client needs)

0

There are 0 best solutions below