This question反映了我的问题。如何在SQLite中执行此操作?
我尝试使用自联接UPDATE
,在子查询,触发器和类似this的内容中隔离自联接。这是一个例子:
UPDATE stage
SET title =
(
SELECT
prior.title
FROM
stage prior,
stage now
WHERE
prior.rownum+1 = now.rownum
)
WHERE
title is null
答案 0 :(得分:4)
SQLite中的每个表都有一个名为 rowid 的伪列(可以通过几个不同的名称访问:rowid
,oid
,_rowid_
,除非这些名称被分配给其他真实的列。 rowid列本质上是唯一的行标识符,您可以将其用作排序标准和/或条件。
以下查询演示了如何在 rowid 的帮助下解决您的问题:
UPDATE stage
SET title = (
SELECT title
FROM stage AS prev
WHERE title IS NOT NULL AND prev.rowid < stage.rowid
ORDER BY prev.rowid DESC
LIMIT 1
)
WHERE title IS NULL
您可以在this SQLite manual中了解有关 rowid 的更多信息。
答案 1 :(得分:2)
我提出了您提到的问题的解决方案(我在SQL2008,SQLite3和Oracle11g上成功测试过)。我在下面复制了这个解决方案:
CREATE TABLE test(mysequence INT, mynumber INT);
INSERT INTO test VALUES(1, 3);
INSERT INTO test VALUES(2, NULL);
INSERT INTO test VALUES(3, 5);
INSERT INTO test VALUES(4, NULL);
INSERT INTO test VALUES(5, NULL);
INSERT INTO test VALUES(6, 2);
SELECT t1.mysequence, t1.mynumber AS ORIGINAL
, (
SELECT t2.mynumber
FROM test t2
WHERE t2.mysequence = (
SELECT MAX(t3.mysequence)
FROM test t3
WHERE t3.mysequence <= t1.mysequence
AND mynumber IS NOT NULL
)
) AS CALCULATED
FROM test t1;
-- below here it was only tested in SQLite3, but I believe it should
-- work on other DBMS since it uses standard/non-proprietary SQL
UPDATE test
SET mynumber = (
SELECT t2.mynumber
FROM test t2
WHERE t2.mysequence = (
SELECT MAX(t3.mysequence)
FROM test t3
WHERE t3.mysequence <= test.mysequence
AND mynumber IS NOT NULL
)
);