0

这是 Postgres更新记录的此问题的副本,它满足具有递增数字的条件,但我需要一种适用于 SQLite3 的方法。

从原始问题中截取:

剪辑

我在 postgres 中有一张这样的表:

Id    Name    local_site_id    local_id
1     A       2                
2     B       2
3     C       1
4     D       2
5     E       1

如何使用 SQL 查询将表更新为此:

Id    Name    local_site_id    local_id
1     A       2                1
2     B       2                2
3     C       1                
4     D       2                3
5     E       1                

现在,所有记录的 local_id 字段都是空的。我想使用从 1 开始的递增数字更新 local_id 值,仅适用于具有local_site_id=2是否可以使用 SQL 的行?

结束片段

我从那里的答案中尝试了这个命令,但它不适用于 SQLite3

update T set local_id=s.rn 
from (select id,row_number() over(order by id) as rn from T where local_site_id=2) s
where T.id=s.id;

如何在 SQLite3 中实现这一点?

4

2 回答 2

1

这应该这样做:

.mode column
.headers on

create table T (Id, Name, local_site_id, local_id);

insert into T values
    (1, 'A', 2, null),
    (2, 'B', 2, null),
    (3, 'C', 1, null),
    (4, 'D', 2, null),
    (5, 'E', 1, null);

update T set local_id = (
    select 
        case local_site_id
            when 2 then (select count(*) 
                         from T t2 
                         where t2.id <= t1.id and local_site_id=2)
            else null
        end
    from T as t1 where T.id=t1.id);

select * from T;

返回:

Id          Name        local_site_id  local_id  
----------  ----------  -------------  ----------
1           A           2              1         
2           B           2              2         
3           C           1                        
4           D           2              3         
5           E           1                        
于 2012-08-30T14:48:07.433 回答
0

I found a way myself. I created a temporary table and then used the "ROWID" internal column of the temporary table to update the original table.

create table temptable as select id from tablename where local_site_id=2;

update tablename 
    set local_id=(select ROWID from temptable where temptable.id=tablename.id)
    where exists (select ROWID from temptable where temptable.id=tablename.id);

But I'll accept Ludo's answer as it doesn't involve creating a new table.

于 2012-08-30T15:05:45.920 回答