【问题标题】:How would one rewrite this raw query in knexjs?如何在 knexjs 中重写这个原始查询?
【发布时间】:2021-08-21 20:16:04
【问题描述】:

我正在尝试在 knex 查询构建器 js 中重写以下内容。

有人知道怎么做吗?

knex.raw(
    /* sql */ `
      UPDATE "product-products_fields" SET value = ?
      WHERE productid = ?
      AND fieldid = (SELECT fieldid FROM "product-fields" WHERE field = ?)`,
   [value, productId, field],
);

【问题讨论】:

    标签: knex.js


    【解决方案1】:

    我会创建 2 个查询:

    const firstQuery = await knex("product-fields")
    .where("field", field)
    .select("fieldid")
    
    const secondQuery = await knex("product-products_fields")
    .update("value", value)
    .where("productid", productId)
    .andWhere("fieldid", firstQuery)
    

    或者类似的东西。

    【讨论】:

    • 这会导致对数据库的一个或两个查询吗?
    • 如您所见,将有 2 个。firstQuery 将获取一个数据,然后,secondQuery 将获取该数据,这将是第二个查询。实际上,您的 sql 查询也包含两部分 - updateselect
    • 你的例子需要 2 次往返还是像我的一样只需要 1 次?
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 2018-09-01
    • 2022-06-27
    • 2021-02-11
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多