【问题标题】:Good way to write sub queries in pg-promise在 pg-promise 中编写子查询的好方法
【发布时间】:2019-09-01 16:44:39
【问题描述】:

如果我必须在单个 API 中执行更多查询,我必须以哪种方法继续 这是在主查询中编写子查询的更好方法吗 不使用 db.task 或 db.tx 否则我必须使用这些方法。 像下面这样

function userChangePassword(req, res) {
    const changePwd = req.swagger.params.body.value;

    const token = req.headers.authorization;
    token.replace('Bearer ', '');
    const decoded = jwt_decode(token);

    const newpass = changePwd.newPassword;
    const user_id = decoded.userId;

    const userSel = `select * from xx."yy" where "userId" = '${user_id}' AND "status" = 1`;
    const updatePwd = `update xx."yy" set "password" = '${newpass}' where "userId" = '${user_id}' `;

    db.query(userSel).then((usrResult) => {
            if (usrResult.length > 0) {
                db.query(updatePwd).then(() => {
                    res.send(response.success("The password has been changed successfully", []));
                });
            } else {
                res.send(response.success("The password has not changed successfully", []));
            }
        })
        .catch((err) => {
            if (util.isError(err)) res.error('NotFoundError', err); // return 404
            else res.error('InternalServerError', err); // else 500
        });
}    

请帮我解决这个困惑.. 谢谢。

【问题讨论】:

  • 你为什么不直接使用上面提到的tasktx 方法呢?见Chaining Queries
  • 感谢您的评论。我使用过 task 和 tx,但我的问题是哪一个是好的方法,并且在查询执行中提供更好的性能。

标签: node.js postgresql pg-promise


【解决方案1】:

如果查询之间存在依赖关系,则必须使用方法task/tx。否则,您可以使用helpers.concat 将查询连接为一个,并将它们作为一个查询执行,这样会更快。如果您希望从多重查询中返回数据,您可以使用方法 multi / multiResult

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    相关资源
    最近更新 更多