使用 javascript mysql 客户端执行 mysql 查询序列的正确方法

Proper way to execute sequence of mysql queries with javascipt mysql client

简单地说:我有一个 table 'a'、一个 table 'b' 和一个多对多 table 'a_b'。我需要在 table 'b' 中插入一行,然后如果插入正确,则使用此行的 id 将其插入 'a_b' 以使其在 [=47] 中引用 id =] 'a'。像这样:

INSERT INTO b (foo) VALUE ('bar');

然后拿这个的结果ID来做

INSERT INTO a_b (a_id, b_id) VALUES ('some_table_a_id', 'generated_b_table_id');

我在 NodeJS 服务器 Express API 上执行 post 请求,所以它看起来像这样:

app.post("/whatever", (req, res) => {
  db.query(insert_into_b_sql, [params], (err, result, fields) => {
    if (!err) {
      db.query(insert_into_a_sql, [params], (err, result, fields) => {
        if (!err) {
          res.sendStatus(200);
        } else {
          throw err;
        }
      });
    } else {
      throw err;
    }
  });
});

我看到很多问题:

  1. 我没有插入行的最后一个 ID,我想我无法获取它。所以我需要在其中进行第三个 SQL 查询来获取 ID。这样做已经感觉不对了,所以我认为嵌套第三个 SQL 查询会更糟。
  2. 我进行了很多 SQL 查询,这可能会导致成本增加。
  3. 如果第一个查询成功,但第二个查询不成功,我需要更多查询来回滚,因为没有提交机制(我不知道)。
  4. 我想我可以使用存储过程,但这里不可能,因为它需要在存​​储库中存储和维护,团队决定避免这种情况。

所以我们到了:按照我描述的方式链接 SQL 查询是否合法?如果是,是否有任何方法可以防止我描述的回滚必要性?否则,考虑到应尽可能避免存储过程,还有哪些其他选择?

我想你正在使用标题中标​​记的 nodejs mysql 库。对于其他库,您可以保留这个概念。

  1. I don't have the last ID of my inserted row, and I don't think I can get it.

方法query() 应该return 最后插入的记录。您可以检查回调中的 resultfields。文档中也指出:https://www.npmjs.com/package/mysql#getting-the-id-of-an-inserted-row

  1. I make many SQL queries, which can result in costs increase once it gets to prod.

是的,但是根据要求,我们必须有 2 个单独的查询。

  1. If the first query succeed, but the second does not, I need more queries to rollback because there is no commit mechanism (not that I know of).

您需要使用交易。一旦事务中的一个命令失败,就可以整体回滚。查看文档 here