select all customers which have no services
I have two MySQL tables, tblclients
and tblservices
. Each record in tblservices
represents a service we provide for a client and there can be many services per client. Both tables have a 'status' field, in tblclients
it is either 'active' or 'inactive' and in tblservices
it is either 'active' or 'terminated'.
I need to write a SQL statement which will output a list of active clients which have no active services so that I can write a php script which will make the clients inactive.
I understand how to list all开发者_开发问答 clients which have a service which is terminated, but I don't understand how to list clients which have no active services (all terminated). Is there a way to query this in SQL using subqueries or the like. So far I have:
SELECT tblclients.id, tblclients.email, tblservices.status
FROM tblclients JOIN tblservices on tblclients.id = tblservices.userid
WHERE tblclients.status="active" AND tblservices.status="terminated";
Try using WHERE [NOT] EXISTS (I've munged your table names for readability):
SELECT * FROM clients WHERE
clients.status = 'active' AND
NOT EXISTS (SELECT * FROM services WHERE
services.userid = clients.id AND
services.status = 'active'
);
This'll give you all your active clients that don't have any active services (these will include clients with no services at all).
Hope this helps!
Update: To exclude clients with no services at all, just add that condition, too:
SELECT * FROM clients WHERE
clients.status = 'active' AND
EXISTS (SELECT * FROM services WHERE services.userid = clients.id) AND
NOT EXISTS (SELECT * FROM services WHERE
services.userid = clients.id AND
services.status = 'active'
);
Change your join to a LEFT JOIN and set a filter for null tblservices.userid.
Assuming tblServices has no records with that client's id....
SELECT tblclients.id, tblclients.email, tblservices.status
FROM tblclients
LEFT OUTER JOIN tblservices on tblclients.id = tblservices.userid
WHERE tblservices.id is null
Feel free to use any field in tblservices for the null test, though I think the id for that table would be best.
If you need to show that as 0 services as a count, use a case statement.
精彩评论