MySql内连接与order by

时间:2014-03-27 00:49:23

标签: mysql sql-order-by inner-join

我有两张桌子USERS和VOTES;

我使用下面代码的两个表进行内连接;

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

我得到了比较结果

我想要最后评论Erric's,而不是Tom&#39。

result

您可以从以下链接

运行代码

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

感谢您的帮助

最好的问候

2 个答案:

答案 0 :(得分:0)

如果您想要一行具有最新值,那么您应该使用not exists而不是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
                 );

答案 1 :(得分:0)

我找到了解决方案 但我不确定它是否足够快

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

您可以从下面的链接中查看

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