将一个 table 中一列的 SUM 插入 JAVA 中另一个 table 的另一列

Inserting SUM of one column from one table to another column of another table in JAVA

我的 database.I 中有 F_table 和 S_table 想将我的 F_table 的 Quantity_column 的所有值的总和插入到Total_column 的 S_table。为此,我必须在 JAVA?

中写下什么

假设,我有两个 table,一个是 Product_table,另一个是 Stock_table.In,Product_table 有 ID、名称、数量等列。在 Stock_table 中有像 ID、TotalProduct 这样的列。现在我想要 Product_table 的 Quantity 列的所有原始总和,并将其插入到 Stock_table 的 TotalProduct 列中。每次我添加任何产品及其数量时,TotalProduct 都会自动增加。为了得到我必须在 JAVA?

中做的事情

抱歉,如果这是一个新手类型的问题。我其实是初学者。如果有人帮助我,那就太好了。

如果我没理解错的话,您想从产品 table 中获取每个 ID 的总数量,然后将其插入库存 table,是吗?

下面会得到数量的总和,按 id 分组:

select id, sum(quantity) from product_table group by id;

所以如果你有:

1, test1, 5
1, test2, 10
2, test3, 20
2, test4, 1
3, test5, 5

你会得到类似的东西:

1, 15
2, 21
3, 5

然后将这些插入正确的 table。

要将两者结合起来,您应该可以执行以下操作:

insert into stock_table 
select id, sum(quantity) from product_table group by id;

请记住,这完全是您要问的 SQL 问题。但是要使其与 jdbc/java 相关,这样的 jdbc 将是:

String sql = "insert into stock_table select id, sum(quantity) from product_table group by id";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.executeUpdate();

stmt.close();

您可能希望通过 stmt.executeUpdate() 检查行数 updated/inserted。