在另一列中插入列的最后一个 ID table PostgreSQL

insert last id of column in another column table PostgreSQL

我正在尝试插入来自 table 的列代码,计算来自 table 股票的列代码的最后一个 ID,这是我的请求,但它不起作用。

  String sql1="INSERT INTO calcul (idproduit,inventaire,consomation,date,quantite,designation,dateper,ppa,tr,net,code) "
           + "VALUES ('"+codeP+"',"+newQuant+","+0+",'"+datestock+"',"+newQuant+",'"+designation+"','"+datePer+"',"+PPA+","+TR+","+NET+",SELECT MAX(code) from stock );";
     
       stmt.executeUpdate(sql1);

您需要修改查询以包含子查询(替换值)。我不打算在这里重复整个 Whosebug 的答案,但是我想给你一些已经得到答案的问题的参考,请参阅 here and here

在你的,我会写查询如下:

"INSERT INTO calcul (idproduit,inventaire,consomation,date,quantite,designation,dateper,ppa,tr,net,code) SELECT '"+codeP+"',"+newQuant+","+0+",'"+datestock+"',"+newQuant+",'"+designation+"','"+datePer+"',"+PPA+","+TR+","+NET+",MAX(code) from stock;

你的查询有点乱,所以我想用更通用的形式把它放在下面

INSERT INTO calcul (col1, col2, ....,coln) SELECT col1, col2, ..., MAX(code) FROM stock;