Conditional update in SQLite

后端 未结 3 1322
终归单人心
终归单人心 2020-12-06 18:31

Can I create in SQLite a statement like this?

update books set
(if number_of_pages > 0 then number_of_pages = number_of_pages - 1)
where book         


        
3条回答
  •  悲&欢浪女
    2020-12-06 18:59

    If you just want to conditionally update some rows and leave others intact, this should do:

    update books
    set number_of_pages = number_of_pages - 1
    where number_of_pages > 0 AND book_id = 10
    

    If you want to update all rows (with book_id = 10) to different values, you can use 2 statements with "opposite" conditions. Assuming 0 is the "other" value, that would look like this:

    update books
    set number_of_pages = number_of_pages - 1
    where number_of_pages > 0 AND book_id = 10
    
    update books
    set number_of_pages = 0
    where number_of_pages <= 0 AND book_id = 10
    

    Or just use CASE as others have suggested.

提交回复
热议问题