【问题标题】:Adding a custom column to a knex query with PostgreSQL使用 PostgreSQL 向 knex 查询添加自定义列
【发布时间】:2020-04-02 18:23:33
【问题描述】:

我对于为 PostgreSQL 编写一般查询非常陌生,更不用说 Knex,所以我很感激有人可以提供任何帮助。

PostgreSQL v10.12
Knex v0.20.13
节点v12.16.0

假设我有一个数据库,其中包含以下条目:

id   |  int1  |  int2
_____________________
1        5        10
2        6        15

我的 knex 查询看起来像这样:

db // This is my knex connection
  .from('items AS item')
  .select(
    'item.id',
    'item.int1',
    'item.int2'
   )

我将如何在结果中添加一列来求和 int1 和 int2?

id   |  int1  |  int2  |  sum
_______________________________
1        5        10       15
2        6        15       21

【问题讨论】:

    标签: node.js postgresql knex.js


    【解决方案1】:

    首先,为了不跳过一个步骤。

    我们要使用 Knex 构建的查询是:

    Select id, int1, int2, (int1 + int2) as sum from items;
    

    此查询将获取items 的所有常规列,并添加一个名为sum 的新列。

    为了使用 Knex 构建此查询:

    db.select('id', 'int1', 'int2', db.raw('(int1 + int2) as sum')).from('items');
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2017-10-12
      • 2022-01-01
      • 2018-01-14
      • 2022-11-21
      • 2013-11-10
      相关资源
      最近更新 更多