Simulate ORDER BY in SQLite UPDATE to handle uniqueness constraint

前端 未结 1 805
南笙
南笙 2021-01-05 06:27

I have a table in SQLite 3 thus:

sqlite> .schema
CREATE TABLE table1 (id INTEGER PRIMARY KEY NOT NULL,
                     title TEXT UNIQUE NOT NULL,
           


        
相关标签:
1条回答
  • 2021-01-05 06:58

    You are right that the problem appears because SQLite checks the constraints after every row update and not at the end of statement or the end of transaction.

    I see this workaround to the problem (of SQLite not having implemented UPDATE correctly). Assuming that the priority column does not have any negative values, we can use them (negative values) as temporary to avoid the UNIQUE constraint errors:

    UPDATE table1 SET priority = - (priority + 1) WHERE priority > 1 ;
    
    UPDATE table1 SET priority = - priority WHERE priority < 0 ;
    
    0 讨论(0)
提交回复
热议问题