I'm trying to accomplish this with one SQL statement, but I guess I'm a little out of practice, as I'm coming up with nothing.
Let's say I have two entries in a database:
Now, I want to pull the total records where id=1234 and I also want to pull the data from the most recent entry. I try:Code:id record date data1 data2 1 1234 2009-12-10 00:00:01 abc def 2 1234 2009-12-10 02:00:00 def ghi
and it returns:Code:SELECT *,COUNT(*) AS TOTAL FROM history WHERE record='1234' ORDER BY date DESC LIMIT 1
It does this with ASC order, too. If I try it with MAX(date), I get the right date, but the data fields are not correct for the date.Code:+--------+----------+---------------------+-------+-------+-------+ | log_id | record | date | data1 | data2 | total | +--------+----------+---------------------+-------+-------+-------+ | 2 | 1234 | 2009-12-10 02:00:00 | abc | def | 2 | +--------+----------+---------------------+-------+-------+-------+ 1 row in set (0.00 sec)
--EDIT--
I found using a sub query will work, but is there a more efficient way?
Code:SELECT *,(SELECT COUNT(*) FROM history WHERE record='1234') AS total FROM history WHERE record='1234' ORDER BY date DESC LIMIT 1



LinkBack URL
About LinkBacks
Reply With Quote



Bookmarks