sqlite group by update where max

时间:2014-06-30 20:28:53

标签: sql sqlite

我正在尝试对SQLite表进行更新,只有当该行具有该分组中特定列的最大值时才将列值设置为1。

例: 按BookID分组,仅当BookVersion为最大值时设置Latest = 1

BookID BookVersion 
==================
ABC      1
ABC      2
ABC      3
DEF      1

Output
BookID BookVersion Latest
==========================
ABC        1         0
ABC        2         0
ABC        3         1
DEF        1         1

我试过

update Books set Latest=1 from Books INNER JOIN (select BookId, MAX(BookVersion) from Books GROUP BY BookId );

我收到:

SQL error: near "from": syntax error

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

SQLite不支持update join。我认为你可以用where子句做同样的事情:

update Books
    set Latest = 1 
    where not exists (select 1
                      from books b2
                      where b2.bookid = Books.bookid and
                            b2.bookversion > Books.bookversion
                     );

这里的逻辑是“更新bookid没有更大版本号的行。”