views:

38

answers:

3

Hi,

I have a table (Counts) with many entries like this:

ID | userid | count | entrydate

where ID is an autoinc PK, userid refers to my Users table, count is a random integer, and entrydate is a unix timestamp.

I also have a table called Listmembers:

listid | userid

where both fields together are PK, and listid refers to some list information.

I want to write a query that returns the most recently inputted count value for each user in a specific list.

I tried variations with GROUP BY (only returns the first inputted data item per userid, not the most recent), with ORDER BY (but this returns all counts for the relevant users), with user selection inside my query (where userid IN (..)) and outside the query (join listmembers on ..). No query resulted in what i want to achieve :-/

A: 

How about using max(entryDate)?

dmr
i don't want the entrydate though, i want the count that comes with the max(entrydate)
Tominator
A: 
SELECT c.count FROM Counts as c, Listmembers as l
 WHERE l.userid = c.userid 
        AND l.listid = 'specific_value'
        AND c.entrydate = MAX(c.entrydate)
Eton B.
mysql tells me "Invalid use of group function"
Tominator
Implied joins, very bad.
HLGEM
+3  A: 
select c.userid, c.count  from counts C
inner join (select userid, max(entrydate)  
            from Counts group by userid) g 
   on c.userid =g.userid and c.entrydate = g.entrydate
inner join Listmembers L on l.userid = c.userid
where l.listid = @desiredList 

(Note: I've never actually used mysql. That should be the T-Sql syntax, but it should be standard enough to work on an SQL)

James Curran
i see what you did there, but is it efficient when there are many entries in Counts? To select from it twice?
Tominator
That's going to work. The only thing you forgot is filtering by listid. Consider adding it.
Ihor Kaharlichenko
yes, it does work (with slight modifications not important to the question), so now i'm wondering efficiency :-) Anyone have data on that?
Tominator
@Ihor: Did our posts cross in the ether? I have added filtering, but I though I had it up before your comment.
James Curran