2015-08-13 58 views
2

我在rethinkdb中執行以下SQL查詢時遇到了一些問題,我想根據user_count獲取社區中5個最受歡迎的通道。MySQL與RethinkDB不同計數類型查詢

SELECT 
    channels.*, 
    COUNT(distinct channel_users.user_id) as user_count 
FROM channel_users 
LEFT JOIN channels ON 
    channels.id = channel_users.channel_id 
WHERE channels.community_id = "MY_COMMUNITY_ID" AND channels.type = 'public' 
GROUP BY channel_id 
ORDER BY user_count DESC 
LIMIT 5 

這就是我在ReQL中得到的這個,它給我一個頻道列表,我懷疑還需要更多的map/reduce嗎?

r.db('my_db') 
.table('channel_users') 
.filter({ community_id : 'MY_community_id' }) 
.orderBy(r.desc('created_at')) 
.eqJoin('channel_id', r.table('channels')) 
.map(function(doc){ 
    return doc.merge(function(){ 
     return { 
      'left' : null, 
      'right': {'user_id': doc('left')('user_id')} 
     } 
    }) 
}) 
.zip() 
.run(function(err, channels){ 
    console.log(err, channels); 
    next(); 
}); 

而且表的設計看起來像:

channel_users

id | channel_id | community_id | role | user_id 

渠道

id | community_id | name | user_id (creator) 

感謝任何幫助!謝謝

回答

0

這是做你想做的?

r.table('channels').filter(
    {community_id: 'MY_COMMUNITY_ID', type: 'public'} 
).merge(function(channel) { 
    return {user_count: r.table('channel_users').filter({channel_id: channel('id')}).count()}; 
}).orderBy(r.desc('user_count')).limit(5) 

(請注意,你可以,如果你創建channel_id二級指標使用getAll代替filter合併內加速此。)

+0

這樣的作品,並感謝您的提示,我會做那。 – jesperado