sql - 使用 knex 连接子查询

标签 sql knex.js

我想要实现的是加入子查询,即:

select A.*, B.*, C.* from A
join C on C.id = A.c_id
join B on B.id = (
    select id from B
    where B.created_at > C.created_at
    order by B.created_at asc
    limit 1
)

我尝试过的:

...
.leftJoin('B', 'B.id', knex.select(...
...

这不起作用。 还尝试过:

...
.leftJoin('B', function () {
  this.on('B.id', knex.select(...
})
...

这也不起作用。我怎样才能用 knex 实现这一目标?

最佳答案

在将查询生成器传递给 join 时,knex 中似乎仍然存在一些错误。

无论如何,这就是实现该查询的方法:

knex('A')
  .join('C', 'C.id', 'A.c_id')
  .join('B', 'B.id', (builder) => {
    builder
      .select('id')
      .from('B')
      .where('B.created_at', '>', knex.ref('C.created_at'))
      .orderBy('B.created_at', 'desc')
      .limit(1);
  })

https://runkit.com/embed/sqavpxeds1cn

关于sql - 使用 knex 连接子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53570116/

相关文章:

knex.js - 使用 knex 从 postgresql jsonb 检索特定 key

sql - 将 sas 变量传递给 sql pass through 语句

mysql - 初学者 - 查询标记为文本的列中的值

php - 将特定日期的多个时差相加

mysql - 如果存在则更新,否则插入不起作用

mysql - Knex 不返回插入 ID

node.js - 错误: Transaction rejected with non-error: undefined

mysql - Knex.js - 如何使用表达式更新字段

sql - Postgres 将时间戳与长 unix 时间戳进行比较

mysql - 如何与 bookshelf 和 knex 中的联接表交互?