查询: UPDATE item_table SET field1=field1_spanish, field2=field2_spanish;
问题:如果<{strong> field1
不为空,我如何使用field1_spanish
更新field1_spanish
?如果field2
不为空,我也希望field2_spanish
更新field2_spanish
。
谢谢!
答案 0 :(得分:10)
http://sqlfiddle.com/#!5/58554/1
update
item_table
set
field1 = coalesce(field1_spanish, field1),
field2 = coalesce(field2_spanish, field2)
coalesce()
函数将返回传递给它的第一个参数,该参数不为null。所以在这种情况下,由于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
答案 1 :(得分:1)
假设所有这些列都在同一个表中:
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
中删除相关条目并从临时表中插入新数据(确保使用所有这些的事务!)。