postgresql - 如何使用 KnexJS 创建值列表

标签 postgresql knex.js

我想生成一个用于查询的动态表。为此,我想使用此处记录的 PostgreSQL VALUES 列表功能:https://www.postgresql.org/docs/13/queries-values.html

SQL 看起来像这样:

with my_values (id, "name") as (
    values (1, 'one'), (2, 'two'), (3, 'three')
)
select *
from my_values mv
join some_other_table sot
    on sot.value_id = mv.id

我在 KnexJS 文档中找不到任何支持生成上述 SQL 的内容,除了对整个查询使用 raw 之外,这有点违背了使用 KnexJS 的意义。

有没有办法在 KnexJS 中为部分查询创建值列表?

最佳答案

为了构造以下查询

with my_values as (
    Select *
    from (values(1, 'one'), (2, 'two'), (3, 'three')) as inner (id, name)
)
select *
from my_values mv
join some_other_table as sot on sot.value_id = mv.id

问题是 knex 不支持您编写的列列表定义。 Postgress,支持这个

SELECT * FROM (VALUES (1, 'one'), (2, 'two'), (3, 'three')) AS t (num,letter);

因此,上面的查询可以这样构建:

const vals = [
  { id: 1, name: 'one' },
  { id: 2, name: 'two' },
  { id: 3, name: 'three' },
];

const params = vals.reduce((result, { id, name }) => result.concat(id, name), []);


await db
  .with(
    `my_values`,
    db.raw(
      `Select * from (values ${vals.map(() => `(?, ?)`).join(',')}) as inner (id, name)`,
      params
    )
  )
  .select('*')
  .from('my_values mv')
  .join('some_other_table', 'some_other_table.value_id', 'mv.id');

生成

{
  bindings: [ 1, 'one', 2, 'two', 3, 'three' ],
  sql: 'with `my_values` as (Select * from (values (?, ?),(?, ?),(?, ?)) as inner (id, name)) select * from `my_values_mv` inner join `some_other_table` on `some_other_table`.`value_id` = `mv`.`id`'
}

关于postgresql - 如何使用 KnexJS 创建值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67281982/

相关文章:

javascript - 在 Node.js 和 Knex 中向现有表添加列

node.js - Node js + 对象 js + Postgresql。类型 '{ token: string }' 的参数不可分配给类型 'PartialUpdate<User>' 的参数

mysql - 如何将 MySQL MEMORY 存储引擎与 Knex 结合使用?

ruby - 在 Postgres/Ruby 中比较日期和月份

postgresql - 如何使用 Postgis 缓冲点?

postgresql - 带有插入但没有复制操作的postgres转储

sql - 如何选择具有相同属性的有限数量的行?

json - Zend 错误连接

node.js - 传递到 Handlebars 的数据未显示

javascript - 不知道如何等待 Promise