【发布时间】: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。
谢谢!
【问题讨论】:
查询: UPDATE item_table SET field1=field1_spanish, field2=field2_spanish;
问题:我怎样才能用field1_spanish 更新field1 仅当 field1_spanish 不为空?如果field2_spanish 不为空,我也想用field2_spanish 更新field2。
谢谢!
【问题讨论】:
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
【讨论】:
假设所有这些列都在同一个表中:
update some_table
set field1=field1_spanish,
field2=field2_spanish
where field1_spanish is not null
and field2_spanish is not null;
如果field1 和field2 在table 中,而*_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 用于第二种方法。
【讨论】: