【问题标题】:Merging two SQL statement in one , to update a row in a table if it meet certain conditions将两条SQL语句合二为一,满足一定条件时更新表中的一行
【发布时间】:2020-04-16 11:01:38
【问题描述】:

我正在开发一个使用 JDBC 更新库存和下订单的应用程序。

我正在存储产品,如果请求的数量少于存储的数量,我想更新产品,如果数量等于数据库中当前库存的数量,我想从数据库中删除产品.

我使用了两种不同的语句,但我只想使用其中一种。例如,如果我想将订单添加到数据库中,系统将请求的内容是名称和产品数量。产品数量将从数据库中产品的总数量中减去。伪代码是

IF product quantity - user quantity =0 THEN DELETE product FROM database

ELSE UPDATE product quantity TO product quantity-user quantity ON THE database

product quantity=quantity of the product in the database

user quantity=quantity requested by the user

我现在拥有的Prepared Statements是这两个

UPDATE products SET quantity=quantity-? WHERE product_name=?

DELETE FROM products WHERE product_name=?

如果可能,我想将它们合并为一个

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。
  • 您不能在同一个语句中执行删除和更新。从您的 Java 代码控制此流程有什么问题?
  • 您有两种完全不同的行为(是否删除行)。这不会很漂亮或易于维护。查看数据库的 SQL 方言,了解如何执行条件。你也许可以。否则查看存储过程。
  • 为什么要删除产品?
  • @Strawberry 因为如果产品不再可用,所以无法订购,如果产品数量少于一定数量,其他选择是使用条件

标签: java mysql sql jdbc


【解决方案1】:

在生产系统中,您会做这种事情。

如你所说,为了订单,请执行此操作。

UPDATE products SET quantity=quantity-? WHERE product_name=?

然后,在夜间或每周清理中执行此操作以清除没有剩余数量的行。

DELETE FROM products WHERE quantity = 0

当您想知道实际可用的产品时,您会这样做

SELECT product_name, quantity FROM products WHERE quantity > 0

这里的概念:数量为零的行是“不可见的”,即使它们没有被删除。

如果这是我的系统,我不会删除行。一方面,当您获得更多库存产品时会发生什么?

【讨论】:

    【解决方案2】:

    一种方法是通过在连接 URL 中将 MySQL Configuration Property allowMultiQueries 设置为 true 来放松安全性。

    那么就可以同时执行两条SQL语句了:

    String sql = "UPDATE products" +
                   " SET quantity = quantity - ?" +
                 " WHERE product_name = ?" +
                   " AND quantity >= ?" +
                 ";" +
                 "DELETE FROM products" +
                 " WHERE product_name = ?" +
                   " AND quantity = 0";
    try (PreparedStatement stmt = conn.prepareStatement(sql)) {
        stmt.setInt(1, userQuantity);
        stmt.setString(2, productName);
        stmt.setInt(3, userQuantity);
        stmt.setString(4, productName);
        stmt.execute();
        int updateCount = stmt.getUpdateCount();
        if (updateCount == 0)
            throw new IllegalStateException("Product not available: " + productName);
        // if you need to know if product got sold out, do the following
        stmt.getMoreResults();
        int deleteCount = stmt.getUpdateCount();
        boolean soldOut = (deleteCount != 0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      相关资源
      最近更新 更多