【问题标题】:How do I select tail with nulls in sqlite?如何在 sqlite 中选择带有空值的尾部?
【发布时间】:2017-12-14 21:46:53
【问题描述】:

我有一个 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 语句中完成此操作。

【问题讨论】:

  • 为什么不只是delete from tail where val is null?对 sqlite 不太熟悉,所以无法帮助那里的语法。
  • @JacobH 我需要所有的 val=NULL 除了尾部的用于其他计算。

标签: sql sqlite null sequence gaps-and-islands


【解决方案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);

【讨论】:

  • 它有效,谢谢戈登。顺便说一句,'val is null and' 不是多余的还是我错过了什么?
  • @MichałŠrajer。 . .是的。在这种情况下,它是多余的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 2011-08-14
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多