更新Null值

问题描述 投票:2回答:2

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
sql sqlite
2个回答
4
投票

SQLite中的每个表都有一个名为rowid的伪列(可以在几个不同的名称下访问:rowidoid_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

这是一个demo on SQL Fiddle

你可以在this SQLite manual上阅读更多关于rowid的内容。


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
       )
);
© www.soinside.com 2019 - 2024. All rights reserved.