MySQL INSERT IF (custom if statements)

前端 未结 5 1461
后悔当初
后悔当初 2020-11-27 04:37

First, here\'s the concise summary of the question:

Is it possible to run an INSERT statement conditionally? Something akin to this:

IF(         


        
5条回答
  •  生来不讨喜
    2020-11-27 04:52

    Try:

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

    If a product with id equal to 2 exists and the qty_on_hand is greater or equal to 20 for this product, then an insert will occur with the values product_id = 2, and qty = 20. Otherwise, no insert will occur.

    Note: If your product ids are note unique, you might want to add a LIMIT clause at the end of the SELECT statement.

提交回复
热议问题