我在rethinkdb中实现以下SQL查询时遇到一些问题,我想根据user_count获取社区中最受欢迎的5个频道。
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中得到的,这只是给我一个频道列表,我怀疑这里需要更多的地图/缩减?
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 :(得分: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)
(请注意,如果在getAll
上创建辅助索引,则可以在合并中使用filter
而不是channel_id
来提高速度。)