0

我正在尝试UPDATE与 Knex 一起写一份声明。

我想输出的 SQL 是:

UPDATE customers SET "month_value" = "src"."month_value", "modified" = NOW() FROM ( SELECT COALESCE(SUM("month_value"), 0) AS month_value FROM "customer_products" WHERE "active" = true AND "customer_id" = 111781 ) src WHERE "id" = 111781

到目前为止,这是我的 JavaScript:

db.knex.table('customers')
      .where('id', '=', ':customerId')
      .from(db.sequelize.knex.raw('(' +
        'SELECT' +
        'COALESCE(SUM("month_value"), 0) AS month_value' +
        'FROM "customer_products"' +
        'WHERE "active" = true' +
        'AND "customer_id" = ?' +
        ') AS src' +
        'WHERE "id" = :customerId', [customerId]))
      .update({'month_value': src.month_value,
               'modified': NOW(),
              })

但是,它给了我这个错误:

{"message":"ApiErrorMiddleware ReferenceError: src is not defined","level":"info"}
{"message":"UnknownErrorMiddleware ReferenceError: src is not defined","level":"info"}

我做错了什么?

4

1 回答 1

0

这对我有用:

db.sequelize.knex.table('customers')
  .where('id', '=', ':customerId')
  .from(db.sequelize.knex.raw('('
    + 'SELECT'
    + 'COALESCE(SUM("month_value"), 0) AS month_value'
    + 'FROM "customer_products"'
    + 'WHERE "active" = true'
    + 'AND "customer_id" = :customerId'
    + ') src'
    + 'WHERE "id" = :customerId', [customerId]))
  .update({
    month_value: 'src.month_value',
    modified: 'NOW()',
});
于 2019-06-16T12:29:42.483 回答