0

首先,这是问题的简明摘要:

是否可以有条件地运行 INSERT 语句?类似于这样的东西:

IF(expression) INSERT...

现在,我知道我可以使用存储过程来做到这一点。

现在,我想这样做

假设我们有以下 3 个表:

products: id, qty_on_hand
orders: id, product_id, qty
roomTable :id,product_id,room_number,booked_status

现在,假设有 20 个房间(产品 id 2)的订单进来。我们首先从订单表中检查给定 product_id 的总数量为 total_qty 和 total_qty < qty_on_hand 如果它返回 true 然后插入订单值并在最后一次预订后更新 1 个房间_status= 'Y' room from roomTable with booking_status ='Y' 并给出那个房间的 id。

问题是我无法进行连接查询。到目前为止我做了什么-

    INSERT INTO orders(product_id, qty)
SELECT 2, 20 FROM products WHERE id = 2 AND qty_on_hand >= 20
4

2 回答 2

1

For those of you who need more detail around how this technique works from Mt. Schneiders,

INSERT INTO orders(product_id, qty)
SELECT 2, 20 
  FROM products 
 WHERE id = 2 AND qty_on_hand >= 20 + (select sum(qty) from orders where product_id = 2)

What is going on here is that the result of the select statement is hard coded. In this case we are taking INSERT INTO orders(product_id, qty) VALUES(2, 20) and replacing VALUES(2,20) with SELECT 2, 20. The result of the SELECT is hard coded but only returns a value if the condition is met.

I found this article that explains this technique more in depth:

http://boulderapps.co/dont-insert-when-maximum-is-reached

于 2014-05-09T20:16:38.823 回答
0

不会是这样吗?

INSERT INTO orders(product_id, qty)
SELECT 2, 20 
  FROM products 
 WHERE id = 2 AND qty_on_hand >= 20 + (select sum(qty) from orders where product_id = 2)

因此,如果最后一个订单数量加上正在插入的订单的数量小于或等于手头的数量,它将不会插入。

于 2013-01-25T19:05:18.263 回答