SQLite-根据新值更新旧值

时间:2018-07-11 10:06:18

标签: sql sqlite sql-update

我有一张下表,其中包含以下数据:

------------------------------------------
|ID|Name|Value|State |Version|Replaced_by|
------------------------------------------
|1 |Joe |10   |New   |1      |NULL       |
------------------------------------------
|2 |Ben |15   |New   |1      |NULL       |
------------------------------------------

然后我添加例如2个新行:

------------------------------------------
|ID|Name|Value|State |Version|Replaced_by|
------------------------------------------
|1 |Joe |10   |New   |1      |NULL       |
------------------------------------------
|2 |Ben |15   |New   |1      |NULL       |
------------------------------------------
|3 |Joe |20   |New   |2      |NULL       |
------------------------------------------
|4 |Dan |10   |New   |1      |NULL       |
------------------------------------------

然后我要执行一个更新,其中更新 Name State组的最旧 Version Replaced_by ,具有 Name State 组的最新 Version ID 值,因此看起来像这样:

------------------------------------------
|ID|Name|Value|State |Version|Replaced_by|
------------------------------------------
|1 |Joe |10   |New   |1      |3          |
------------------------------------------
|2 |Ben |15   |New   |1      |NULL       |
------------------------------------------
|3 |Joe |20   |New   |2      |NULL       |
------------------------------------------
|4 |Dan |10   |New   |1      |NULL       |
------------------------------------------

虽然我找到了解决我问题的好方法,但它在SQLite中不起作用。我在另一个问题中受到https://www.jetbrains.com/help/youtrack/standalone/v1-IssueWorkItem.html答案的启发。

UPDATE
  table1
SET
  replaced_by = i.id
FROM
  (
    SELECT
      id, name, state, version
    FROM
      table1 t1
    WHERE
      version = (
        SELECT
          MAX(version)
        FROM
          table1
        WHERE
          t1.name = table1.name
          AND t1.state = table1.state
          AND t1.replaced_by IS NULL
      )
  ) i
WHERE
  table1.name = i.name
  AND table1.state = i.state
  AND table1.version = i.version
  AND table1.replaced_by IS NULL

基本上,Replaced_by列用作其他版本控制工具,可以简化从表中选择数据的工作。

期待任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以将existsupdate语句一起使用:

update table
  set Replaced_by = (select max(t1.id) 
                     from table t1 
                     where t1.name = table.name and 
                           t1.State = table.State
                    )
where exists (select 1 
              from table t1 
              where t1.name = table.name and 
                    t1.State = table.State and 
                    t1.id <> table.id
              ) and replaced_by IS NULL;

答案 1 :(得分:0)

您是否考虑过一次插入每个数据 您可以使用:

更新(表名) 设置名称='丹' 其中ID = 2

更新(表名) 设定值='20' ID = 1

更新(表名) 设置版本='1' ID = 1

更新(表名) 设置replacedby ='3' ID = 1

对所有更新执行此操作