【问题标题】:How to do `UPDATE...SET...FROM` using knex?如何使用 knex 执行 `UPDATE...SET...FROM`?
【发布时间】:2021-10-06 22:15:07
【问题描述】:

使用 knex 表达UPDATE...SET...FROM SQL 语句的最简洁方式是什么?这是我目前所拥有的:

  const query =
    knex('user_subscriptions').update(subscription).toQuery() +
    knex.raw(
      ' from plans p where customer_id = ? and p.id = us.plan_id ' +
        'returning us.*, p.name',
      [customer_id]
    );

我这样做的原因是我想有效地从相关表(JOIN 样式)中返回一个字段,而不需要单独的查询。

【问题讨论】:

    标签: sql postgresql knex.js postgresql-10


    【解决方案1】:

    按照官网提示:knexjs.org/#Builder-update

    knex('user_subscriptions')
      .returning(['us.*', 'plans.name', 'customer_id'])
      .where({
      customer_id: '?',
      plans.id:  us.plan_id
    })
      .update({
        subscription : '?
      })
    

    做:

    update `user_subscriptions` set `subscription ` = '?' where `customer_id` = '?' and 'plans.id' = 'us.plan_id'
    

    返回:

    [ us.*: ..., plans.name: ...,  customer_id: ... ]
    

    【讨论】:

    • 我们如何在该查询中获取plans 表? p.id 没有任何意义.. 它没有引用任何内容。
    • 我刚刚对您的问题进行了编辑。希望这会有所帮助:)
    • 不要误会,但在回答人们关于该主题的问题之前,您可能应该学习 SQL。
    【解决方案2】:

    为什么不一直构建:

    let query = knex.raw(
     'update user_subscriptions '
      + 'set subscription = ?, '
      + 'where p.id = us.plan_id '
      + 'and customer_id = ? '
      + 'returning us.*, p.name '
      , [customer_id]
        );
    
    results = query.rows
    

    【讨论】:

    • 我已经在使用knex.raw(),这是显而易见的路线。
    猜你喜欢
    • 2017-04-30
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多