我想生成一个用于查询的动态表。为此,我想使用此处记录的 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/