我有一个sqlite3数据库,其中每一行都有自动递增的id
和一些可以是NULL
的值。我需要删除带有空值的尾部(理想情况下,保留此段中最旧的空记录)。
例如,在这里,我想删除 id = 12..16 (或理想情况下为13..16)的行。
任何想法如何在sqlite中完成?
CREATE TABLE tail (id INTEGER PRIMARY KEY, val TEXT);
INSERT INTO "tail" VALUES(1,'5');
INSERT INTO "tail" VALUES(2,'7');
INSERT INTO "tail" VALUES(3,'100');
INSERT INTO "tail" VALUES(4,'150');
INSERT INTO "tail" VALUES(5,NULL);
INSERT INTO "tail" VALUES(6,NULL);
INSERT INTO "tail" VALUES(7,'120');
INSERT INTO "tail" VALUES(8,'150');
INSERT INTO "tail" VALUES(9,'152');
INSERT INTO "tail" VALUES(10,NULL);
INSERT INTO "tail" VALUES(11,'152');
INSERT INTO "tail" VALUES(12,NULL);
INSERT INTO "tail" VALUES(13,NULL);
INSERT INTO "tail" VALUES(14,NULL);
INSERT INTO "tail" VALUES(15,NULL);
INSERT INTO "tail" VALUES(16,NULL);
我可以通过两个步骤轻松完成,例如:
to_delete = []
for row in query("SELECT * FROM tail ORDER BY -id"):
if row.id IS NOT NONE:
break
to_delete.add(row.id)
# optionally: to_delete.remove_last()
query("DELETE FROM tail WHERE id IN (?)", to_delete)
但这不是在事务中,我觉得有一些巧妙的技巧可以用来在单个sqlite语句中实现这一点。
答案 0 :(得分:1)
您可以使用:
delete from tail
where id > (select max(t2.id) from tail t2 where t2.val is not null) and
val is null and
id <> (select max(t3.id) from tail t3 where t3.val is null);