MySQL Conditional Insert

前端 未结 13 1137
予麋鹿
予麋鹿 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:25

    What you want is INSERT INTO table (...) SELECT ... WHERE .... from MySQL 5.6 manual.

    In you case it's:

    INSERT INTO x_table (instance, user, item) SELECT 919191, 123, 456 
    WHERE (SELECT COUNT(*) FROM x_table WHERE user=123 AND item=456) = 0
    

    Or maybe since you're not using any complicated logic to determiante whether to run the INSERT or not you could just set a UNIQUE key on the combination of these two columns and then use INSERT IGNORE.

    0 讨论(0)
  • 2020-11-22 10:27
    Insert into x_table (instance, user, item) values (919191, 123, 456) 
        where ((select count(*) from x_table where user=123 and item=456) = 0);
    

    The syntax may vary depending on your DB...

    0 讨论(0)
  • 2020-11-22 10:28

    So this one stands for PostgreSQL

    INSERT INTO x_table
    SELECT NewRow.*
    FROM (SELECT 919191 as instance, 123 as user, 456 as item) AS NewRow
    LEFT JOIN x_table
    ON x_table.user = NewRow.user AND x_table.item = NewRow.item
    WHERE x_table.instance IS NULL
    
    0 讨论(0)
  • 2020-11-22 10:29

    If your DBMS does not impose limitations on which table you select from when you execute an insert, try:

    INSERT INTO x_table(instance, user, item) 
        SELECT 919191, 123, 456
            FROM dual
            WHERE NOT EXISTS (SELECT * FROM x_table
                                 WHERE user = 123 
                                   AND item = 456)
    

    In this, dual is a table with one row only (found originally in Oracle, now in mysql too). The logic is that the SELECT statement generates a single row of data with the required values, but only when the values are not already found.

    Alternatively, look at the MERGE statement.

    0 讨论(0)
  • 2020-11-22 10:37

    With a UNIQUE(user, item), do:

    Insert into x_table (instance, user, item) values (919191, 123, 456) 
      ON DUPLICATE KEY UPDATE user=123
    

    the user=123 bit is a "no-op" to match the syntax of the ON DUPLICATE clause without actually doing anything when there are duplicates.

    0 讨论(0)
  • 2020-11-22 10:39

    In case you don't want to set a unique constraint, this works like a charm :

    INSERT INTO `table` (`column1`, `column2`) SELECT 'value1', 'value2' FROM `table` WHERE `column1` = 'value1' AND `column2` = 'value2' HAVING COUNT(`column1`) = 0
    

    Hope it helps !

    0 讨论(0)
提交回复
热议问题