SQLite UPDATE现在可以正常工作,或者我做错了

时间:2019-02-14 19:04:46

标签: sqlite

当前表格问题:

rowid: 1 | 2 | 3 | 4 | 5
id:    3 | 4 | 7 | 9 | 10 

尝试实现以下目标:

rowid: 1 | 2 | 3 | 4 | 5

id:    1 | 2 | 3 | 4 | 5 

我尝试了许多不同的SQL变体而没有成功,这是我正在测试的最新版本:

  

更新问题SET id = rowid;

有人可以建议我如何解决这个问题,因为我已经用Google搜索,但是找不到解决方案?

1 个答案:

答案 0 :(得分:1)

我不认为您的问题完全涵盖了问题的各个方面。

理论上要有一个表(之前的表),其中SELECT rowid, id会导致

rowid: 1 | 2 | 3 | 4 | 5
id:    3 | 4 | 7 | 9 | 10 

id 列不得是 rowid 列的别名(否则值将相同)

但是,如果id列是 rowid 列的别名,则这两列将是相同的,因此上面的before表将不是上面的

例如使用:-

--<<<<<<<<<< WORKS >>>>>>>>>>
-- as ID is not an alias of the rowid column update changes id column
DROP TABLE IF EXISTS questionsv3;
CREATE TABLE IF NOT EXISTS questionsv3 (ID INTEGER);
INSERT INTO questionsv3 VALUES (3),(4),(7),(9),(10);
SELECT rowid, id FROM questionsv3;
UPDATE questionsv3 SET id = rowid;
SELECT rowid, id FROM questionsv3;

根据以下结果得到预期结果:-

首先选择(更新前):-

enter image description here

第二选择(更新后)

enter image description here

其他潜在原因

    实际上,按照SQLITE,
  1. rowid 并不是 rowid ,而是一个概念上的想法,应该为1,2,3 ...... (在这种情况下,使用VACUUM,如果rowid没有别名,则可能导致rowid列需要重新编号,如果随后进行更新,则可能导致id重新排序。)

  2. 更新是在尚未提交并回滚的事务中完成的。

您可能希望考虑以下不同表创建的排列(请参见注释):-

-- as ID is an alias of rowid, then rowid is set according to ID so update does nothing
DROP TABLE IF EXISTS questionsv1;
CREATE TABLE IF NOT EXISTS questionsv1 (ID INTEGER PRIMARY KEY);
INSERT INTO questionsv1 VALUES (3),(4),(7),(9),(10);
SELECT rowid, id FROM questionsv1;
UPDATE questionsv1 SET id = rowid;
SELECT rowid, id FROM questionsv1;

-- as ID is an alias of the rowid column, then rowid is set according to the ID so update does nothing
DROP TABLE IF EXISTS questionsv2;
CREATE TABLE IF NOT EXISTS questionsv2 (ID INTEGER PRIMARY KEY AUTOINCREMENT);
INSERT INTO questionsv2 VALUES (3),(4),(7),(9),(10);
SELECT rowid, id FROM questionsv2;
UPDATE questionsv2 SET id = rowid;
SELECT rowid, id FROM questionsv2;

--<<<<<<<<<< WORKS >>>>>>>>>>
-- as ID is not an alias of the rowid column update changes id column
DROP TABLE IF EXISTS questionsv3;
CREATE TABLE IF NOT EXISTS questionsv3 (ID INTEGER);
INSERT INTO questionsv3 VALUES (3),(4),(7),(9),(10);
SELECT rowid, id FROM questionsv3;
UPDATE questionsv3 SET id = rowid;
SELECT rowid, id FROM questionsv3;

--<<<<<<<<<< WORKS >>>>>>>>>>
-- as ID is not an alias of rowid the ID column is updated accordingly
DROP TABLE IF EXISTS questionsv4;
CREATE TABLE IF NOT EXISTS questionsv4 (ID TEXT PRIMARY KEY); -- not an alias of rowid
INSERT INTO questionsv4 VALUES (3),(4),(7),(9),(10);
SELECT rowid, id FROM questionsv4;
UPDATE questionsv4 SET id = rowid;
SELECT rowid, id FROM questionsv4;

--<<<<<<<<<< FAILS >>>>>>>>>>
DROP TABLE IF EXISTS questionsv13;
CREATE TABLE IF NOT EXISTS questionsv13 (ID INTEGER PRIMARY KEY) WITHOUT ROWID;
INSERT INTO questionsv13 VALUES (3),(4),(7),(9),(10);
SELECT id FROM questionsv13;
UPDATE questionsv13 SET id = rowid; -- would fail no such column
SELECT id FROM questionsv13;