So I am trying to run a query that will select, in this case, clients that haven't had an appointment is X amount of time (2 weeks for instance). It boils down to "show me a list of clients that haven't had an appointment in 2 weeks". I'm attempting to solve this in php by doing something like:
$date = new DateTime;
$ago = new DateInterval('P2W');
$target = $date->sub($ago);
//query to select clients that aren't scheduled after the $target date
$clients = ...;
Two tables involved, appt_tbl, and clients_tbl. appt_tbl stores a client_id for each appointment record.
So essentially what I need is to select the "max" appointment for each client, and if it's < my $target date, include them in the query results. I've tried various flavors of queries, queries with sub queries, but I'm stumbling on getting this query right.
My current attempt looks something like:
SELECT *
FROM clients_tbl
INNER JOIN
(
SELECT client_id
FROM appt_tbl
WHERE MAX(appt_date_time) < '2012-07-22'
GROUP BY client_id
) appts ON appts.client_id = clients_tbl.client_id;
This should also include clients that have never been scheduled (IE won't appear in the appt_tbl), but not clients who have an appointment booked in the next two weeks.
SELECT a.*
FROM clients_tbl a
LEFT JOIN appt_tbl b ON
a.client_id = b.client_id AND
b.appt_date_time >= CURDATE() - INTERVAL 2 WEEK
WHERE b.client_id IS NULL
What this query does first (before the WHERE
filtering) is select all clients whether or not they have a scheduled appointment greater than two weeks ago.
If the client does not have an appointment greater than two weeks ago, the values in the joined table will be NULL
. We want all rows where the join conditions did not satisfy (i.e. values in joined table are null), which is done with WHERE b.client_id IS NULL
.
This also includes into the result-set clients who do not have any corresponding appointments at all.
Clients who have appointments in the future are excluded.
There is also no need to construct a datetime string in PHP. You can simply do it straight in the query (although you may pass in the number of weeks ago as a parameter).
This could be simple enough i think.
select users from time_sheet where created_date >= date('2013-12-01');
In your case you got to do like this. Instead of this
WHERE MAX(appt_date_time) < '2012-07-22'
do this
WHERE MAX(appt_date_time) < date('2012-07-22')
That acually makes the date comparision, earlier one was date with string comparision.
Cheers!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With