MySQL INSERT 語句可以有條件嗎?

Susan Sarandon
發布: 2024-11-14 16:25:02
原創
209 人瀏覽過

Can MySQL INSERT Statements Be Made Conditional?

Conditional INSERT Statements in MySQL

Question: Is it feasible to perform an INSERT operation conditionally, akin to an IF statement?

Elaboration:

Suppose we need to place an order for 20 items with product ID 2. To ensure sufficient stock, we first check the quantity on hand:

SELECT IF(
    ( SELECT SUM(qty) FROM orders WHERE product_id = 2  ) + 20
    <=
    ( SELECT qty_on_hand FROM products WHERE id = 2)
, 'true', 'false');
登入後複製

If the result is true, we execute the INSERT query. However, this approach is susceptible to concurrency issues. Multiple simultaneous orders can result in overselling.

Answer:

Yes, conditional INSERT statements are possible using the following syntax:

INSERT INTO TABLE
SELECT value_for_column1, value_for_column2, ...
FROM wherever
WHERE your_special_condition
登入後複製

If the SELECT statement returns no rows (i.e., the special condition is false), no insertion occurs.

Example:

For the given schema:

products: id, qty_on_hand
orders: id, product_id, qty
登入後複製
insert into orders (product_id, qty)
select 2, 20
where (SELECT qty_on_hand FROM products WHERE id = 2) > 20;
登入後複製

This query will only insert a row if there is sufficient stock on hand. Otherwise, it will not execute the insertion.

以上是MySQL INSERT 語句可以有條件嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板