Suppose I have clients and services of the following schema:
create table client (
id INT NOT NULL,
name varchar(100) NOT NULL,
PRIMARY KEY ( id )
);
create table service (
id INT NOT NULL,
client_id INT NOT NULL,
status varchar(36) NOT NULL,
PRIMARY KEY ( id )
);
And the requirement is to select all clients which have all their services deleted (status = ‘DELETED’). What would be the best approach?
My try is:
SELECT DISTINCT service.client_id
FROM service
WHERE service.id NOT IN (SELECT service.id FROM service s WHERE s.status <> 'DELETED' AND s.client_id = service.client_id);
But it only selects client_id, probably need some join.
6
Answers
you can use exists
Schema (MySQL v8.0)
Query #1
View on DB Fiddle
This looks like you need a not exists
If you also need the
service.id
, use a combination of join and exists.You could count existing services and just filter using
HAVING
You can use the
group by
andhaving
clauses, with the condition that the total number of services equals the total number of services with status DELETED:Result :
Demo here
You can do it just with a JOIN: