2008-12-13 35 views
0

我有一個數組填充值(Twitter的ids),我想找到最低的ID和最高的ID之間的缺失數據?分享一個簡單的功能或想法如何做到這一點的任何照顧?如何在數組或mySQL表中查找缺少的數據?

此外,我想知道我是否可以用mySQL做同樣的事情?我有索引的關鍵字。該表現在包含250k行,因此臨時表和聯接不會非常快速或高效。我可以做一個PHP循環來循環訪問數據,但這也需要很長時間和大量的內存。有一個特定的MySQL查詢,我可以運行?或者我可以以某種方式使用從上面的功能與此?

謝謝, 詹姆斯哈蒂格 http://twittertrend.net

回答

1

我也有類似的要求,並寫道,將返回缺少ID列表功能。

--------------------------- 
create function dbo.FreeIDs() 
--------------------------- 
returns @tbl table (FreeID int) 

as 
begin 

    declare @Max int 
    declare @i int 

    select @Max = MAX(ID) from [TheTable] 
    set @i = 0 

    while @i < @Max begin 
      set @i = @i + 1 
      if not exists (select * from [TheTable] where ID = @i) 
      insert into @tbl select @i 
    end 

    return 

end 
1

你指的是連續的ID?

在這種情況下

$new_ids = range($lowid, $highid, 1); 
$ids = array_merge($ids, $new_ids); 
$ids = array_unique($ids); 
sort($ids); 

,並在SQL(與佔位符)

SELECT key, other_data from `table` WHERE key > :low_id AND key < :high_id 
+0

你的sql語句沒有意義嗎?它只會返回最大值和最小值之間的所有ID?它不會找到缺失的值。 – 2008-12-13 02:29:44

+0

你怎麼能找到缺失值...他檢索現有的值,並從整個範圍中減去這些值。應該可以工作 – 2008-12-13 02:33:46

1

你的範圍()給了我一個好主意,因爲唯一保留的唯一密鑰代碼沒有工作,所以我只剩下範圍函數的結果。

然而,這工作:

$diff = array_values(array_diff(range(min($array), max($array), 1), $array)); //returns array of incomplete values