【问题标题】:How to update records that satisfies a condition with incrementing number in SQLite3?如何更新满足 SQLite3 中递增数字条件的记录?
【发布时间】:2012-08-30 13:51:18
【问题描述】:

这是 Postgres Update records that satisfies a condition with incrementing number 的这个问题的副本,但我需要一种适用于 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?

结束片段

我从那里的answer 尝试了这个命令,但它不适用于 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 中实现这一点?

【问题讨论】:

    标签: sql sqlite sql-update


    【解决方案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                        
    

    【讨论】:

    • 太棒了..我自己通过创建一个新表发现了一个混乱的方式..但我会接受你的正确答案.. :)
    【解决方案2】:

    我自己找到了方法。我创建了一个临时表,然后使用临时表的“ROWID”内部列来更新原始表。

    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);
    

    但我会接受 Ludo 的回答,因为它不涉及创建新表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2013-01-20
      • 2021-06-14
      • 1970-01-01
      相关资源
      最近更新 更多