【问题标题】:SQLite Update columns only if value is not empty仅当值不为空时 SQLite 更新列
【发布时间】:2012-03-21 22:59:58
【问题描述】:

查询: UPDATE item_table SET field1=field1_spanish, field2=field2_spanish;

问题:我怎样才能用field1_spanish 更新field1 仅当 field1_spanish 不为空?如果field2_spanish 不为空,我也想用field2_spanish 更新field2

谢谢!

【问题讨论】:

    标签: database sqlite


    【解决方案1】:

    http://sqlfiddle.com/#!5/58554/1

    update
      item_table
    set
      field1 = coalesce(field1_spanish, field1),
      field2 = coalesce(field2_spanish, field2)
    

    coalesce() 函数将返回传递给它的第一个非空参数。所以在这种情况下,由于 field2_spanish 为 null,它会将 field2 设置为 field2(基本上什么都不做)。

    为了支持空字符串和 NULL 值,试试这个: http://sqlfiddle.com/#!5/b344f/3

    update
      item_table
    set
      field1 = case when coalesce(field1_spanish, '') = '' then
                field1
               else
                field1_spanish
               end,
      field2 =  case when coalesce(field2_spanish, '') = '' then
                field2
               else
                field2_spanish
               end
    

    【讨论】:

    • 顺便说一句 - sqlfiddle.com 是我的网站
    • 很棒的网站和答案!谢谢!
    • @JakeFeasel - 优秀的网站!我真希望它不会劫持我的后退按钮,但是......
    • @JackManey 它并没有真正劫持您的后退按钮,而只是在您运行查询时向您的浏览历史记录添加更多状态。充分点击“返回”,在完成之前的工作后,您最终应该离开该站点。
    • 嗯,空字符串和null是不一样的。您将不得不这样做:sqlfiddle.com/#!5/b344f/3
    【解决方案2】:

    假设所有这些列都在同一个表中:

    update some_table
    set field1=field1_spanish,
    field2=field2_spanish
    where field1_spanish is not null
    and field2_spanish is not null;
    

    如果field1field2table 中,而*_spanish 列在table_spanish 中,那么...嗯,SQLite doesn't support a from clause in an update statement,所以您必须执行相关子查询。假设table 的主键为id,被table_spanish 引用,您可以这样做:

    update table a
    set field1=(select s.field1_spanish 
        from table_spanish s 
        where field1_spanish is not null
        and s.id=a.id),
    field2=(select s.field2_spanish 
        from table_spanish s 
        where field2_spanish is not null
        and s.id=a.id);
    

    或者您可以通过连接填充临时表,然后从 table 中删除相关条目并从临时表中插入新数据(确保所有这些都使用事务!)。

    Hat tip to martin clayton 用于第二种方法。

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 2021-06-18
      • 2013-03-09
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多