代码之家  ›  专栏  ›  技术社区  ›  yaylitzis

基于SQLITE中其他列的记录更新列

  •  0
  • yaylitzis  · 技术社区  · 6 年前

    我有一张交易记录表 sqlite 我给它加了一个新的专栏。我想要的是根据相同行的记录填充新列。例如

    productId         brc                newColumn
       10032         10032-100101          32-A
       10231         10231-100102          231-B
    

    我已成功获得newColumn的所需输出:

    //The below statement gives me the newColumn result
    select cast(substr(productId, 2, 5) as integer) || 
    case 
        when cast(substr(brc, 37, 1) as integer) == 0 then ''
        when cast(substr(brc, 37, 1) as integer) == 1 then '-Α'
        when cast(substr(brc, 37, 1) as integer) == 2 then '-Β'
        when cast(substr(brc, 37, 1) as integer) == 3 then '-Γ'
        when cast(substr(brc, 37, 1) as integer) == 4 then '-Δ'
    when cast(substr(brc, 37, 1) as integer) == 5 then '-Ε'     
    END as newColumn
    from TRANSACTIONS
    

    现在,我要更新表!我试过:

    update TRANSACTIONS
    set newColumn = (    
       select cast(substr(productId, 2, 5) as integer) || 
       case 
           when cast(substr(brc, 37, 1) as integer) == 0 then ''
           when cast(substr(brc, 37, 1) as integer) == 1 then '-Α'
           when cast(substr(brc, 37, 1) as integer) == 2 then '-Β'
           when cast(substr(brc, 37, 1) as integer) == 3 then '-Γ'
           when cast(substr(brc, 37, 1) as integer) == 4 then '-Δ'
       when cast(substr(brc, 37, 1) as integer) == 5 then '-Ε'      
       END from TRANSACTIONS
       )
    
    where brc = brc; 
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   DinoCoderSaurus    6 年前

    你不需要内心 select newColumn 从给定行中的数据。

    在其他数据库中,我看到这样的查询给出了一个关于“multiple rows returned”(由内部select返回)的错误。在sqlite中并非如此。它可能用第一行的值更新所有行。

    where t1.brc = t2.brc 在内部选择。但这使得数据库做了更多的工作。