SQLite Query to Insert a record If not exists

前端 未结 2 1466
粉色の甜心
粉色の甜心 2020-12-15 17:49

I want to insert a record into a sqlite table if its actually not inserted.

Let\'s say it has three fields pk, name, address

I want to INSERT new record with

相关标签:
2条回答
  • 2020-12-15 18:14

    If you can't make use of a UNIQUE INDEX in combination with INSERT INTO or INSERT OR IGNORE INTO, you could write a query like this;

    INSERT INTO table (column)
    SELECT value
    WHERE NOT EXISTS (SELECT 1 
                      FROM table 
                      WHERE column = value)
    
    0 讨论(0)
  • 2020-12-15 18:22

    Yes, you can do that with a single query.

    INSERT ON CONFLICT IGNORE should help you: http://www.sqlite.org/lang_conflict.html

    Put a unique key on the name, this will create a conflict when you try inserting a record if the name already exists.

    The default is ABORT, so without the IGNORE, the statement will return an error. If you don't want that, use IGNORE.

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