使用另一行中的字段在Sqlite中更新

时间:2014-08-06 10:33:12

标签: sql sqlite sql-update database-performance

有没有办法在Sqlite中简化此更新查询?

update people set
phone = (select phone from people where id=2),
email = (select email from people where id=2)
where id=1;

查询显然会将某些字段从一个人复制到另一个人。

如果对几个字段进行此操作,这对我来说似乎非常低效,因为它执行了很多子查询。

任何优化?

1 个答案:

答案 0 :(得分:1)

UPDATE语法不允许一次查找多个值。

可以使用REPLACE:

INSERT OR REPLACE INTO people(id, phone, email, other, fields)
SELECT old.id, new.phone, new.email, old.other, old.fields
FROM people AS old,
     people AS new
WHERE old.id = 1
  AND new.id = 2

...但是这会在重新插入之前删除记录,这会更糟糕。

最简单的方法是使用两个命令:

SELECT phone, email FROM people WHERE id = 2;
UPDATE people SET phone = ?, email = ? WHERE ID = 1;