I have a MySQL table targeted_refills
with columns: id
(unique, primary key), pat_name
, pat_phone
, rx_number
, drug_name
, qty_disp
, last_date
, qty_left
, price_code
, last_price
, last_contact
, doc_name
, ehf
, userid
What I'm trying to do is list one record for each userid
. The record I want listed is the most recent one based on the field last_date
however if there is more than one record for that user with the most recent date then I want it to select the field with the largest value in the field last_price
. In the rare event that there are two records with matching last_date
and last_price
(shouldn't happen but is possible), I really don't care which is chosen so it can be chosen off the largest value of id
since that is unique and the primary key.
EDIT:
I've tried this query that I pieced together from another person's question:
SELECT t1.*
FROM `targeted_refills` AS t1
LEFT OUTER JOIN `targeted_refills` AS t2
ON t1.userid = t2.userid
AND (t1.last_date < t2.last_date
OR (t1.last_date = t2.last_date AND t1.last_price < t2.last_price))
WHERE t2.userid IS NULL;
and it does a reasonable job of getting where I want to go, but it's pulling a few more records than I want. I'm comparing now to see what extra records it's pulling and why. It also takes a long time to run.