“Insert if not exists” statement in SQLite

后端 未结 4 952
借酒劲吻你
借酒劲吻你 2020-11-22 12:14

I have an SQLite database. I am trying to insert values (users_id, lessoninfo_id) in table bookmarks, only if both do not exist before

4条回答
  •  青春惊慌失措
    2020-11-22 12:42

    If you never want to have duplicates, you should declare this as a table constraint:

    CREATE TABLE bookmarks(
        users_id INTEGER,
        lessoninfo_id INTEGER,
        UNIQUE(users_id, lessoninfo_id)
    );
    

    (A primary key over both columns would have the same effect.)

    It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:

    INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)
    

提交回复
热议问题