I have a table:
id | score | date
bob | 40 | 2010-1-1
bob | 70 | 2010-1-15
sue | 55 | 2010-1-1
sue | 80 | 2010-2-1
I want to query for either the score for a user on a specific date OR, if no score exists for that user on that date,return the score from the most recent date for that user.
Is there a way to do this without a sub-query?
For instance, if I do:
SELECT score
FROM table
WHERE id = '$id'
AND IFNULL(
date = DATE(FROM_UNIXTIME($date)),
MAX(date)
)
I would get no result, as the id does not show up for the most recent date.
Update
Felix reminded me I can't use aggregate functions in the WHERE clause, so now I'm wondering if there is a pseudo-aggregate date function for saying "most recent date" in the where clause, and if so, if I can specify the user when using THAT function?
Update 2
So this is what I have gotten to work, but I still don't know if it's the best way to go (ie, do I need the nested query?):
SELECT score
FROM table
WHERE id = '$id'
AND date = IFNULL(
(SELECT date FROM table
WHERE id = '$id' AND
date = DATE(FROM_UNIXTIME($date))
),
(SELECT MAX(date) FROM table
WHERE id = '$id'
)
)