【问题标题】:PostgreSQL Get holes in index columnPostgreSQL 在索引列中获取漏洞
【发布时间】:2015-12-24 10:46:26
【问题描述】:

我想查询一个表中不存在的数据并不容易,但也许这里有一些技巧可以在一个整数列(行索引)中实现漏洞。
这是一个说明具体情况的小表:

DROP TABLE IF EXISTS examtable1;
CREATE TABLE examtable1 
   (rowindex integer primary key, mydate timestamp, num1 integer);

INSERT INTO examtable1 (rowindex, mydate, num1)
VALUES (1,  '2015-03-09 07:12:45', 1),
       (3,  '2015-03-09 07:17:12', 4),
       (5,  '2015-03-09 07:22:43', 1),
       (6,  '2015-03-09 07:25:15', 3),
       (7,  '2015-03-09 07:41:46', 2),
       (10,  '2015-03-09 07:42:05', 1),
       (11,  '2015-03-09 07:45:16', 4),
       (14,  '2015-03-09 07:48:38', 5),
       (15, '2015-03-09 08:15:44', 2);


SELECT rowindex FROM examtable1;

通过显示查询,我列出了所有使用的索引。
但我想获得(比如说)遗漏的前五个索引,以便我可以使用它们在所需的 rowindex 处插入新数据。
在具体示例中,结果将是:2、4、8、9、12 表示未使用的索引。

这里有什么技巧可以构建一个会给出 n 个缺失索引的查询吗?
实际上,这样的表可能包含许多行,“洞”可以在任何地方。

【问题讨论】:

标签: postgresql


【解决方案1】:

您可以通过使用generate_series() 生成所有数字的列表来执行此操作,然后检查表中不存在哪些数字。

这可以使用外连接来完成:

select nr.i as missing_index
from (
  select i
  from generate_series(1, (select max(rowindex) from examtable1)) i
) nr
  left join examtable1 t1 on nr.i = t1.rowindex
where t1.rowindex is null;

not exists 查询:

select i
from generate_series(1, (select max(rowindex) from examtable1)) i
where not exists (select 1 
                  from examtable1 t1
                  where t1.rowindex = i.i);

我为generate_series() 使用了硬编码的下限,这样您还可以检测到小于最小数字的缺失行索引。

【讨论】:

  • 哇!两个例子都非常有趣且完全可行!我必须研究我以前从未使用过的“generate_series”。我也希望这对大量数据是可以接受的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 2022-01-20
  • 2016-09-28
  • 2022-06-28
  • 1970-01-01
相关资源
最近更新 更多