admin管理员组文章数量:1310099
I'm building a query using knex.js
, given an existing sub query. Following this answer, and this thread in GitHub, I tried the following:
const knex = require("knex")({client: 'pg'});
const subQuery = knex.queryBuilder().select(1);
const query = knex.queryBuilder().select('*').from(subQuery);
console.log(query.toString());
But the result was:
select * from select 1
Which obviously has a syntax error. My expected result is:
select * from (select 1)
Why doesn't it add the parentheses, and how can I change it?
I'm building a query using knex.js
, given an existing sub query. Following this answer, and this thread in GitHub, I tried the following:
const knex = require("knex")({client: 'pg'});
const subQuery = knex.queryBuilder().select(1);
const query = knex.queryBuilder().select('*').from(subQuery);
console.log(query.toString());
But the result was:
select * from select 1
Which obviously has a syntax error. My expected result is:
select * from (select 1)
Why doesn't it add the parentheses, and how can I change it?
Share Improve this question edited May 23, 2017 at 12:26 CommunityBot 11 silver badge asked Feb 8, 2017 at 15:00 GilZGilZ 6,4775 gold badges32 silver badges40 bronze badges2 Answers
Reset to default 7Your way, how you did it seems correct and I would say that it is bug in knex
why it doesn't work (I'm collaborator in knex
).
Anyways there are couple of ways to do it...
const knex = require("knex")({client: 'pg'});
const subQuery = knex.select(1).as('t1');
const query = knex.select('*').from(subQuery);
console.log(query.toSQL());
{ method: 'select',
options: {},
timeout: false,
cancelOnTimeout: false,
bindings: [],
__knexQueryUid: '69d240ad-f5f8-4bc4-8c1d-fb9432af1da2',
sql: 'select * from (select 1) as "t1"' }
Or you can use older style with function()
subquery, which doesn't require .as()
, but supports it...
const query = knex.select('*').from(sq => sq.select(1));
console.log(query.toSQL());
{ method: 'select',
options: {},
timeout: false,
cancelOnTimeout: false,
bindings: [],
__knexQueryUid: '31beb080-c89a-43b2-b112-546077330e82',
sql: 'select * from (select 1)' }
An ugly (but working) solution I found was using knex.raw
and subQuery.toString
:
const query = knex.queryBuilder()
.select('*')
.from(knex.raw(`(${subQuery})`);
I don't believe this is the best answer, and I'm sure I'm missing something, so I don't accept this answer yet.
本文标签: javascriptSelect from an existing query in knexjsStack Overflow
版权声明:本文标题:javascript - Select from an existing query in knex.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741855125a2401298.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论