sql - 如何在 SQL 中逐行顺序更新 2 个表
问题描述
我需要根据彼此的数据并行更新两个表。
下面是两个表的表结构。
产品表:
ProductId | ProductQuantity | Min Price | Max Price
----------+-----------------+-----------+----------
1 | 122 | 58 | 585
2 | 548 | 45 | 856
订单表:
Order ID | ProductID | ProductOrderQuantity |OfferPrice | OrderProcessDate | Status
---------+-----------+----------------------+-----------+------------------+--------
1 | 2 | 35 | 75 | Null | Placed
2 | 1 | 752 | 258 | Null | Placed
在以下情况下,我需要Status
从Order
表格更新为“确认/拒绝”:
ProductOrderQuantity
应该小于表ProductQuantity
中Product
OfferPrice
应该在Min Price
和之间Max Price
如果两个条件都匹配,则
Status
在Order
表中Confirm/Reject
更新OrderProcessDate
为处理日期
此更新应按顺序对订单表中的每一行进行,并且一旦行中的状态更新为“已确认”,则立即更新ProductQuantity
为ProductQuantity - ProductOrderQuantity
解决方案
你可以检查使用
select 'OK'
FROM Order
INNER JOIN Product ON Product.ProductId = Order.ProductId
WHERE order.ProductOrderQuantity < Product.ProductQuantity
AND order.OfferPrice between Product.min_price and Product.Max_price
最终您可以尝试在 JOIN 中使用更新来检查条件
update Order
SET status = "Confirm/Reject",
OrderProcessDate = GETDATE()
FROM Order
INNER JOIN Product ON Product.ProductId = Order.ProductId
WHERE order.ProductOrderQuantity < Product.ProductQuantity
AND order.OfferPrice between Product.min_price and Product.Max_price
推荐阅读
- python - Python Dataframe根据列名添加新行
- java - 使用 fromCallable/fromSupplier 订阅时无法使用 Mono.error
- heroku - 如何格式化procfile以调用文件夹中的程序?
- java - 打印每个字符两次的字符串
- python-3.x - 如果满足某些条件,如何使用 tkinter 创建弹出消息?
- reactjs - 我什么时候应该通过“className”道具来反应组件?
- arrays - Powershell,根据同一CSV中的其他字段修改CSV字段
- javascript - 钩子在内部是如何实现的?
- node.js - 更新 Paypal 上的自定义字段
- python - 在 Python 中使用退出或退出?