MySQL INSERT IF (custom if statements)

前端 未结 5 1451
后悔当初
后悔当初 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:56

    INSERT INTO TABLE
    SELECT value_for_column1, value_for_column2, ...
    FROM wherever
    WHERE your_special_condition
    

    If no rows are returned from the select (because your special condition is false) no insert happens.

    Using your schema from question (assuming your id column is auto_increment):

    insert into orders (product_id, qty)
    select 2, 20
    where (SELECT qty_on_hand FROM products WHERE id = 2) > 20;
    

    This will insert no rows if there's not enough stock on hand, otherwise it will create the order row.

    Nice idea btw!

提交回复
热议问题