使用 PostgreSQL 向 knex 查询添加自定义列

Adding a custom column to a knex query with PostgreSQL

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

PostgreSQL v10.12
奈克斯 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

首先,为了不漏掉一步

我们要使用 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');