【问题标题】:SQL Server : multiple autoincrement on one columnSQL Server:一列上的多个自动增量
【发布时间】:2012-07-24 21:30:04
【问题描述】:

有一个表格如下:

Id   ||  ParentId ||  Other Columns ... 
=======================================
1    ||  1        || ...
2    ||  1        || ...
3    ||  1        || ...
1    ||  2        || ...
2    ||  2        || ...
3    ||  2        || ...
1    ||  3        || ...
2    ||  3        || ...

[Id] 必须具有基于 [ParentId] 的自动递增值(自己的编号)。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 获取行数并将其设置为特定列
  • 这种情况下我需要锁表

标签: sql-server-2008 auto-increment


【解决方案1】:

试试这个

select ROW_NUMBER() over(partition by parentId order by <any other column>) ID,
ParentId,<other columns>  
from  yourtable

编辑1:

如果要在 where 子句中使用 id

with cte as(                                
select ROW_NUMBER() over(partition by parentId order by <any other column>) ID,
ParentId,<other columns>  
from  yourtable)
select * from cte where ID=(some value)

【讨论】:

  • 我以后需要使用IdParentId作为复合键。所以,如果我删除一些行,它将无法工作
  • @BobSponge:那么您可以将查询包含在公用表表达式中
  • 如果我删除行数将被破坏
  • @BobSponge:删除后再次运行相同的查询时,它将正确排序。
  • @JoeGJoseph 删除后编号必须相同。例如,我有 id 1、2 和 3。我删除了 id=2 的行,并且在表中必须保留 id 1 和 3 的行。下一个插入的行的 id 为 4(对于相同的ParentId)。
【解决方案2】:

演示

http://sqlfiddle.com/#!3/32645/6

更新http://sqlfiddle.com/#!3/32645/13

create table dummy(parentId int)

insert into dummy values(1)
insert into dummy values(1)
insert into dummy values(2)
insert into dummy values(1)
insert into dummy values(4)
insert into dummy values(4)
insert into dummy values(5)
insert into dummy values(1)

select row_number() over (order by parentID) as ID,parentID from dummy

【讨论】:

  • OP 已要求根据 ParentID 列的模式获取 ID 值。您的查询将简单地打印行数
猜你喜欢
  • 2021-01-07
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 2011-11-13
  • 2014-06-28
  • 2017-07-28
  • 1970-01-01
相关资源
最近更新 更多