0

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

3 Answers 3

3
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)

Sign up to request clarification or add additional context in comments.

4 Comments

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

Use max() to do this:

max(entryDate)

1 Comment

i don't want the entrydate though, i want the count that comes with the max(entrydate)
-1
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)

1 Comment

mysql tells me "Invalid use of group function"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.