首页 文章

使用rethinkDB进行左连接查询

提问于
浏览
1

我有两个表, usersauthors . 用户可以是作者,如果是,则在作者文档中有用户的 id .

我想要查询的是非作者的所有用户 . 等效的mySQL查询就像是

select * from users left join authors on users.id=authors.userId
where authors.userId is null

我试过的是

r.db('journa').table('authors').outerJoin(
  r.db('journa').table('users'),
  (author, user) => {
    return author.hasFields({'left': 'claimedByUserId'}).not()
  }
)

但它不起作用 . 有关如何实现它的任何想法?

1 回答

  • 1

    你几乎是正确的方式 . 您不应该在连接表达式中反转,因为它将返回一组所有不匹配的排列,并且您将无法检测到所需的匹配 . 以下查询似乎可以满足您的需求:

    r.db('journa')
        .table('users')
        .outerJoin(
            r.db('journa').table('authors'),
            // This is what two sequences are joined upon
            (user, author) => user('id').eq(author('userId'))
        )
        // Joins return `left` and `right`.
        // If there's nothing at the right side, we assume there was no match
        .filter((lr) => lr.hasFields('right').not())
        // Extracting the left table record only
        .map((lr) => lr('left'))
    

相关问题