【问题标题】:Postgres Express and Node JS API- Multiple queries in one API endpointPostgres Express 和 Node JS API - 一个 API 端点中的多个查询
【发布时间】:2021-03-05 12:24:47
【问题描述】:

我有一个 postgres 数据库,我在三个数据库表中插入数据。因为我想通过单击一个按钮将这些数据插入到所有三个表中,所以我不想要三个不同的 API 端点。由于我是 node js 和 postgres 的新手,我无法将所有三个查询放在一个 api 端点中。直到现在我都被困在这个-

app.post("/input",async(req,res)=>{
    try{
        const {a,b,c,d,e,f,g,h,i}= req.body;
        const newentry=await pool.query(
            "INSERT INTO num(a,b,c) VALUES($1,$2,$3) RETURNING *",
            [a,b,c],
            'INSERT INTO order(d,e,f) VALUES ($1,$2,$3) RETURNING *' ,
            [d,e,f],
            'INSERT INTO quantity(g,h,i) VALUES ($1,$2,$3) RETURNING *' ,
            [g,h,i]

            );

         
            res.json(newentry.rows[0]);
           

        
    } catch(err){
        console.error(err.message);
    }
});

【问题讨论】:

    标签: sql node.js postgresql sql-insert common-table-expression


    【解决方案1】:

    您似乎想要通用表表达式:

    with 
        nums   as (insert into num (a, b, c)     values($1, $2, $3)),
        orders as (insert into "order" (d, e, f) values ($1, $2, $3)
    insert into quantity (g, h, i) values ($1, $2, $3);
    

    这允许在单个语句中运行三个插入查询。

    returning 在这里实际上没有意义:您希望从这三个语句中返回哪些值?返回插入的值不是一个明智的方法:因为您首先传递了这些值,所以您已经知道这些值。

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 2016-06-08
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多