MySQL Conditional Insert

前端 未结 13 1411
予麋鹿
予麋鹿 2020-11-22 09:51

I am having a difficult time forming a conditional INSERT

I have x_table with columns (instance, user, item) where instance ID is unique. I want to insert a new row

13条回答
  •  天涯浪人
    2020-11-22 10:17

    I have found out today that a SELECT statement can have a WHERE condition even if it has no FROM clause and does not read any tables at all.

    This makes it very easy to conditionally insert something using this construct:

    SELECT ... INTO @condition;
    -- or if you prefer: SET @condition = ...
    
    INSERT INTO myTable (col1, col2) SELECT 'Value 1', 'Value 2' WHERE @condition;
    

    Tested this on MySQL 5.7 and MariaDB 10.3.

提交回复
热议问题