2008-12-13 89 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