2015-12-24 36 views
2

我想對於不存在的數據查詢表並不容易,但這裏有一些技巧可以在一個整數列(rowindex)中實現空洞。
下面是說明具體情況,小桌子:PostgreSQL在索引列中獲取空洞

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個缺失索引?
實際上,這樣的表格可能包含許多行,並且「孔」可能在任何地方。

+1

這項工作適合你嗎? http://stackoverflow.com/questions/1312101/how-to-find-a-gap-in-running-counter-with-sql –

+1

一個選項,加入'generate_series(1,MAX(rowindex)' :http://www.postgresql.org/docs/current/static/functions-srf.html – Wolph

+0

Thanks guys。Generate_series似乎是通緝的解決方案。 –

回答

3

您可以使用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()這樣你也會發現失蹤rowindex小於最小的數字。

+0

WOW!非常有趣和完全可行,兩個例子!我必須學習「 generate_series「,這是我之前從未使用過的,也希望這可以在大量數據上正常工作,謝謝。 –