我现在有两个表
如TABLE1  字段名  SN1    类型为INT
  TABLE2  字段名  SN2    类型为 INT
  TABLE3  字段名  SN3    类型为 INT
有一个模块:模块一在不断的往TABLE1(SN1)和TABLE2(SN2)里 写入不连续的正整数。
            而模块二也要往TABLE3里面SN3插入整数,每次插入的数字是所有TABLE1和TABLE2中的SN1和SN2组成的递增数字中的最小缺少值。如
   TABLE1中SN1  1、3
   TABLE2中SN2  5、7
那么模块二第一次插入的必须是 2,之后可以是4等,且TABLE1和TABLE2里面的数字都在不断增多的
我想了个算法很复杂,就是先取出来,再排序,然后在循环查找,
那位能否帮我想下简单的思路,我在DELPHI下开发,可以配合环境特色去做算法。谢谢~!

解决方案 »

  1.   

    最小缺少值<--能不能解释一下这个是什么DD来者@_@
      

  2.   

    那么已经填入Table3的最小缺少值就不能再次使用了?
      

  3.   

    SELECT  TOP (1) abFROM   (SELECT COUNT(a.SN3) AS ab, a.SN3
                           FROM    TABLE3 AS a ,TABLE3 AS b where a.SN3 >= b.SN3
                           GROUP BY a.SN3) 
    WHERE     (ab <> SN3)
    ORDER BY ab
      

  4.   

    上面是取 table3 表中最小缺少值
      

  5.   

    你看看这样的算法是不是符合你的要求set nocount on
    declare @table1 table
    (SN1 int)
    declare @table2 table
    (SN2 int)
    declare @table3 table
    (SN3 int)
    declare @maxvalue intinsert into @table1
    select 1
    union
    select 2
    insert into @table2
    select 4
    union
    select 5select identity(int,1,1)as idx ,*
    into #table
    from
    (
    select SN1
    from @table1
    union
    select SN2
    from @table2
    union
    select SN3
    from @table3)aset @maxvalue=(select max(SN1)from #table)+1insert into @table3
    (SN3)
    select isnull(min(idx),@maxvalue) from #table where idx<>SN1select * from @table3
    drop table #table
    set nocount off
      

  6.   

    1.首先将三个表的SN字段全部union起来,并带上id列写入临时表中2.取得最小的与id列不同的SN字段(如果全部符合表示没有断点),如果没有则通过前面定义的最大值+1来确认应该插入SN3的数值3.插入SN3缺点是,如果最小值(T1和T2的)不是1的话会发生Bug如果需要
    修正方案为将identity(int,1,1)中间的1用变量替代,并将全句改写成字符串测试语句如下set nocount on
    create table #table1 
    (SN1 int)
    create table #table2 
    (SN2 int)
    create table #table3 
    (SN3 int)
    declare @maxvalue int
    declare @minvalue int
    insert into #table3 values(4)
    insert into #table1
    select 2
    union
    select 3
    insert into #table2
    select 5
    union
    select 6
    set @minvalue=(select min(SN1)
    from
    (
    select SN1
    from #table1
    union
    select SN2
    from #table2
    union
    select SN3
    from #table3
    )a)exec('select identity(int,'+@minvalue+',1)as idx ,*
    into #table
    from
    (
    select SN1
    from #table1
    union
    select SN2
    from #table2
    union
    select SN3
    from #table3
    )a
    declare @maxvalue int
    set @maxvalue=(select max(SN1)from #table)+1insert into #table3
    (SN3)
    select isnull(min(idx),@maxvalue) from #table where idx<>SN1select * from #table3
    drop table #table
    drop table #table1
    drop table #table2
    drop table #table3
    ')set nocount off
      

  7.   

    假设表tmp中有tid int 
    下列SQL代码实现你的要求SELECT (CASE WHEN EXISTS(SELECT * FROM TMP b WHERE b.tid = 1) THEN MIN(tid) + 1 ELSE 1 END) as tid FROM tmp WHERE NOT tid IN (SELECT a.tid - 1 FROM tmp a)