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):
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: