Tominator Tominator - 2 years ago 71
SQL Question

Cannot write mysql query i want

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 :-/

Answer Source
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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download