MySQL RethinkDB 的非重复计数类型查询

MySQL distinct count type query with RethinkDB

我在 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 中得到的,它只是给了我一个频道列表,我怀疑这里还需要一些 map/reducing?

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();
});

table 设计如下:

channel_users

id | channel_id | community_id | role | user_id

渠道

id | community_id | name | user_id (creator)

感谢任何帮助!谢谢

这是你想要的吗?

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 来加快速度。)