“Insert if not exists” statement in SQLite

后端 未结 4 917
借酒劲吻你
借酒劲吻你 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:49

    If you have a table called memos that has two columns id and text you should be able to do like this:

    INSERT INTO memos(id,text) 
    SELECT 5, 'text to insert' 
    WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
    

    If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

    I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

    I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

提交回复
热议问题