简体   繁体   English

SQLite-将表更新为顺序编号行

[英]SQLite - update table to number rows sequentially

I have table like this: 我有这样的表:

CREATE TABLE Scan
(Id Integer,
Ordinal Integer)

INSERT Scan VALUES(10, 1)
INSERT Scan VALUES(20, 1)
INSERT Scan VALUES(30, 8)
INSERT Scan VALUES(40, 10)

I'd like to update Ordinal column so all the numbers become sequential like so(in case of duplicate Ordinal order by Id): 我想更新Ordinal列,以便所有数字都这样变成连续的(如果ID重复Ordinal顺序):

Id Ordinal
10 1
20 2
30 3
40 4

Is it possible with plain SQL in SQLite? 在SQLite中使用普通SQL是否可能?

SQLite doesn't really have a good way of doing this. SQLite确实没有这样做的好方法。 Here is one approach that isn't particularly efficient: 这是一种效率不高的方法:

update scan
    set ordinal = (select count(*)
                   from scan s2
                   where s2.ordinal < scan.ordinal or
                         s2.ordinal = scan.ordinal and s2.id <= scan.id
                  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM