Question

i have two tables USERS and VOTES;

i do inner join with two tables with below code;

select *, count(*) as people_count from users inner join votes 

on users.id=votes.user_id and votes.choise_id=1 

group by users.country, votes.choise_id 

order by votes.time desc;

USERS AND VOTES TABLES

i get bellow result

i want last comment that Erric's, not Tom's

result

you can run the code from below link

http://www.sqlfiddle.com/#!2/69cc95/3

thanks for your help

Best Regards

Was it helpful?

Solution

i find a sollution but i m not sure if it is fast enough

select * , count(*) as people_count from 

(select * from votes v 
 inner join users u
 on v.user_id=u.id
 where v.choise_id=1
 order by v.time desc
) t

group by t.country

you can examine from below link

http://www.sqlfiddle.com/#!2/69cc95/40

OTHER TIPS

If you want one row with the latest value, then you should use not exists rather than group by:

select *,
       (select count(*) from votes where v.choise_id = 1) as people_count
from users u inner join 
     votes v
     on u.id = v.user_id and v.choise_id = 1 
where not exists (select 1
                  from users u2 join
                       votes v2
                       u2.id = v2.user_id
                  where u2.country = u.country and
                        v2.choise_id = v.choise_id and
                        v2.time > v.time
                 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top