填充空白ID MySQL
我有一张如下表:填充空白ID MySQL,mysql,database,Mysql,Database,我有一张如下表: +----+-------+ | id | name | +----+-------+ | 1 | John | | 3 | Bob | | 4 | Alice | +----+-------+ < P> 假设使用SQLServer(您已经标记了SQLServer和MySQL这里)看起来好像您依赖于身份> /COD>属性以可靠地提供序号;没有。根据文件规定: 标识列可用于生成键值。身份 列上的属性可保证以下内容: 事务中的连续值-插入多行的事务不保证为 行,
+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 3 | Bob |
| 4 | Alice |
+----+-------+
<如果我添加一个新行,我如何使用函数/触发器自动填充空白ID(例如ID 2,然后4, 5,…,n)?< /P> < P> <强>假设使用SQLServer(您已经标记了SQLServer和MySQL这里)看起来好像您依赖于<代码>身份> /COD>属性以可靠地提供序号;没有。根据文件规定: 标识列可用于生成键值。身份 列上的属性可保证以下内容:
- 事务中的连续值-插入多行的事务不保证为
行,因为表上可能会发生其他并发插入。如果
值必须是连续的,然后事务应使用
表上的独占锁或使用可序列化隔离级别 - 服务器重新启动或其他故障后的连续值-出于性能原因和某些原因,SQL server可能会缓存标识值
数据库故障或
服务器重启。这可能会导致标识值在
插入。如果间隙不可接受,则应用程序应使用
它自己生成键值的机制。使用序列生成器
使用NOCACHE选项可以将间隙限制为
从未承诺过
行号()
:
对于ID,不太可能有一个好的理由让它们保持连续性。ID值中有“间隙”并不重要,因为(外键)约束和索引并不关心是否有间隙。尝试以下解决方案:
CREATE TABLE temp1 (
id int,
name varchar(100)
);
select l.id + 1 as id,l.[name]
from temp1 as l
left join temp1 as r on l.id + 1 = r.id
union all
Select * from temp1
order by id
您可以创建一个序列表,在加入表之后,您可以获得变量中缺少的值,如下所示
create table #temp(id int, name varchar(20))
insert into #temp values (1 , 'John'),(3, 'Bob'),(4, 'Alice')
create table #sequence (id int not null primary key);
insert into #sequence(id)
select 1
union all select 2
union all select 3
union all select 4
union all select 6
union all select 7
union all select 8
union all select 9
union all select 10
union all select 15
union all select 16
union all select 17
union all select 18
union all select 19
union all select 20
declare @Id int
select @Id = min (start) from(
select l.id + 1 as start from #sequence as l
left outer join #temp as r on l.id + 1 = r.id
where r.id is null
)a;
select @Id
输出为-
2
,之后您可以在任何SQL操作中使用此变量。您好,您正在询问MySQL、SQL server或其他方面的信息??在这种情况下,SGBD的使用和版本的使用非常重要。请提供更多信息。
create table #temp(id int, name varchar(20))
insert into #temp values (1 , 'John'),(3, 'Bob'),(4, 'Alice')
create table #sequence (id int not null primary key);
insert into #sequence(id)
select 1
union all select 2
union all select 3
union all select 4
union all select 6
union all select 7
union all select 8
union all select 9
union all select 10
union all select 15
union all select 16
union all select 17
union all select 18
union all select 19
union all select 20
declare @Id int
select @Id = min (start) from(
select l.id + 1 as start from #sequence as l
left outer join #temp as r on l.id + 1 = r.id
where r.id is null
)a;
select @Id