【问题标题】:Select from multiple table with knex.js使用 knex.js 从多个表中选择
【发布时间】:2017-11-08 13:25:39
【问题描述】:

如何运行此查询:

select * from table1, table2;

使用 knex.js?

我试过了:

const knex = require('knex')({
  client: 'sqlite3',
  connection: { filename: ':memory:' },
})

async function main() {
  await knex.schema.createTable('table1', table => table.string('field1'))
  await knex.schema.createTable('table2', table => table.string('field2'))
  await knex.insert({ field1: 'value' }).into('table1')
  await knex.insert({ field2: 'value' }).into('table2')
  await knex.from('table1', 'table2')   // first attempt
  await knex.from(['table1', 'table2']) // second attempt
}

main().catch(err => {
  console.error(err)
})

我使用 env DEBUG='knex:query' 运行该代码并得到以下输出:

create table `table1` (`field1` varchar(255))
create table `table2` (`field2` varchar(255))
insert into `table1` (`field1`) values (?)
insert into `table2` (`field2`) values (?)
select * from `table1`
select * from `table1` as `0`, `table2` as `1`

显然,select 声明不是我所期望的。

PS:

如果您将此问题标记为与this one 重复,则不是。 问题的重点不同,答案在that question 没有回答我的问题。

【问题讨论】:

    标签: knex.js


    【解决方案1】:
    knex.from('table1').crossJoin('table2')
    

    生成sqlselect * from table1 cross join table2

    我正在使用 postgres,而不是 sqlite 进行测试,但是这两个语句得到了相同的输出:

    select * from table1, table2;
    select * from table1 cross join table2;
    

    【讨论】:

      【解决方案2】:

      人们总是可以将knex.raw 用于特定于数据库和任何其他复杂的自定义逻辑。

      试试这个(它会产生所需的输出):

      knex
          .select('*')
          .from(knex.raw('table1, table2'))
      

      【讨论】:

        猜你喜欢
        • 2018-04-15
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        • 2021-11-02
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多