2014-03-27 73 views
-1

我有兩個表USERS和VOTES;MySql內部加入訂單

我做兩個表與內部聯接以下代碼;

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的,不是湯姆的

result

你可以從下面的鏈接

運行代碼http://www.sqlfiddle.com/#!2/69cc95/3

感謝您的幫助

問候

+0

您是分組由'country'檢查,所以你只能得到一個排的每個國家。如果你想要所有的行,刪除'group by'。 –

+0

我只希望只有一行評論像下面 eric - 我們 - 2 --- 1 ---即時同意湯姆---日期---- 2 –

回答

0

我找到一個sollution 但我不知道它是否足夠快

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

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 
       ); 
+0

它給了people_count = 1,我也需要了解有多少票。 您可以在這裏看到您的代碼http://www.sqlfiddle.com/#!2/69cc95/22 –

+0

感謝您的effor。我想我找到一些溶劑並分享它 –