Postgresql中这个CTE的最终方式

时间:2017-05-18 10:28:45

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

我的目标是在Soggetto条目中获取id并将其填入tipo和tipo2。我无法通过nodejs中的pg找出如何以正确的方式在Postgres中写入此CTE。我有点困惑。

var query = client.query('WITH retid AS (INSERT INTO "Soggetto" (nome, cognome, "regSociale", "partIVA") VALUES ($1, $2, $3, $4) RETURNING id ), INSERT INTO "Tipologia" (privato, azienda) VALUES ($5, $6) SELECT id FROM retid, INSERT INTO "Tipologia2" (cliente, fornitore) VALUES ($7, $8) SELECT id FROM retid ',
                      [sog.nome, sog.cognome, sog.ragioneSociale, sog.partitaIva, sog.cliente, sog.fornitore, sog.privato, sog.azienda], function(err, result){
                        if(err){
                          console.log(err);
                        }else{
                          res.writeHead(200, {'content-type': 'text/plain'});
                          res.end('Insert ok');
                        }
                      });

1 个答案:

答案 0 :(得分:2)

语法不正确。目前还不清楚你想要什么,但每个CTE都需要自己的名字。所以,像这样:

WITH retid AS (
      INSERT INTO "Soggetto" (nome, cognome, "regSociale", "partIVA")
          VALUES ($1, $2, $3, $4)
          RETURNING id
     ),
     t as (
      INSERT INTO "Tipologia" (privato, azienda)
          VALUES ($5, $6)
     ),
     t2 as (
      INSERT INTO "Tipologia2" (cliente, fornitore)
          VALUES ($7, $8)
     )
SELECT id
FROM retid;