我有两张桌子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;
我得到了比较结果
我想要最后评论Erric's,而不是Tom&#39。
您可以从以下链接
运行代码http://www.sqlfiddle.com/#!2/69cc95/3
感谢您的帮助
最好的问候
答案 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
您可以从下面的链接中查看