【问题标题】:Obtain the missing number [duplicate]获取缺失的号码[重复]
【发布时间】:2012-08-22 11:30:10
【问题描述】:

可能重复:
Find the smallest unused number in SQL Server

我在 Sql server 中有这张表

ID |  LetterID | LetterName

ID => int 和身份

LetterID => int and unique and NotNull

字母名 => 字符串

LetterID 填写我的 C# 应用程序和用户设置的编号。例如 1,2,3,4,5,...,100,..(每行增加一个单位)现在我的 @ 987654324@ 是100 但有时用户从表中删除一行,例如删除LetterID50 的行,现在插入新行(在应用程序中)我建议他LetterID 选择50,怎么能我从表中得到丢失的数字?

【问题讨论】:

  • 为什么要填补这些空白?
  • 我们是否担心多用户和锁定在这里?即您是否必须从其他用户锁定这 50 个?
  • 为什么要填补这些空白? – 蒂姆·施梅尔特 => 是的
  • @hamidrezamansouri - Tim 的问题是为什么?“是”的答案不合适。如果您想回复某人,请以@、他们的用户名和空格开头。他们会收到您的回复通知。

标签: c# sql sql-server


【解决方案1】:
var output =  Enumerable.Range(1, list.Max(item => item.LetterID))
          .Except(list.Select(item => item.LetterID))

【讨论】:

  • 您能否进一步解释一下这个来源?
  • 这段代码除了两个列表。代码是否针对高行优化?
  • @hamidrezamansouri:此来源使用 LINQ to Entities
【解决方案2】:

获取空白/缺失的行

SELECT TOP 1 x.LetterID +1 
FROM tablename x
WHERE NOT EXISTS(SELECT * FROM tablename xx WHERE xx.LetterID  = x.LetterID  + 1)
ORDER BY x.LetterID

【讨论】:

    【解决方案3】:
    select t1.ID, t1.LetterID-1 
    from yourtable t1
        left join yourtable t2 
    on t1.LetterID = t2.LetterID+1
    and t1.ID = t2.ID
    where t2.ID is null
    and t1.LetterID>(select MIN(LetterID) from yourtable where ID = t1.ID)
    

    【讨论】:

      【解决方案4】:
      ;with cte as
      (
        select max(LetterID) as id from your_table
        union all
        select id-1 from cte where id>1
      )
      select cte.id as LetterID
      from cte
      left join your_table yt on cte.id=yt.LetterID
      where yt.id is null
      order by cte.id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 1970-01-01
        • 2013-02-19
        • 1970-01-01
        • 2011-11-17
        • 2014-04-16
        相关资源
        最近更新 更多