【问题标题】:Sqlite: how to split multiple table update into several statementsSqlite:如何将多个表更新拆分为多个语句
【发布时间】:2018-04-23 21:17:55
【问题描述】:

Sqlite 更新不支持连接。对于以下示例,

update Employee t0 LEFT join EmployeeDetail t1 on (t1.id=t0.id) 
set t0.status=1, t1.salary=t1.salary+10000
where t1.salary < 50000 and t0.status=0

要更新的列属于不同的表,它们在哪里 条款。如果使用子查询拆分成如下两条语句:

update Employee set status=1
where id in (select t0.id from
Employee t0 LEFT join EmployeeDetail t1 on (t1.id=t0.id) 
where t1.salary < 50000 and t0.status=0)

update EmployeeDetail set salary=salary+10000
where id in (select t1.id from
Employee t0 LEFT join EmployeeDetail t1 on (t1.id=t0.id) 
where t1.salary < 50000 and t0.status=0)

执行一个语句会影响另一个语句,因为它会影响 where 子句 限制。

Sqlite 数据库如何解决这个问题?

【问题讨论】:

  • status 在哪个表中?两者都有。
  • Employee 表中的状态。已更新。

标签: sql database sqlite join sql-update


【解决方案1】:

我建议将要更新的 id 存储在临时表中,然后使用它。这还可以防止竞争条件并简化锁定。

create temporary table ids as 
    select e.id
    from Employee e join
         EmployeeDetail ed
         on e.id = ed.id
where ed.salary < 50000 and e.status = 0;

然后简单地做:

update employee e
    set status = 1
    where id in (select id from ids);

update employeedetail
    set salary = salary + 10000
    where id in (select id from ids);

【讨论】:

  • 有没有办法在内存中创建临时表并在事务结束时自动销毁?
  • @Sunnyday 。 . .临时表通常在 SQLite (sqlite.org/inmemorydb.html) 中得到有效处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多