关于数据库中的AK(Alternate Key)
替代键的解释(alternate key)
所谓唯一性约束(unique constraint)不过是数据表内替代键的另一个名称而已。替代键(alternate key)可以是数据表内不作为主键的其他任何列,只要该键对该数据表唯一即可。换句话说,在唯一列内不允许出现数据重复的现象。比方说,你可以用车辆识别代号(VIN)作为汽车(Automobile)数据表的替代键,在汽车数据表里,主键是汽车识别号(Automobile Identification),这是一种由系统自动生成的ID。你可以在汽车表内对VIN施加唯一性约束,同时再创建一个需要VIN的表。在这个新表内可以声明外键指向汽车表。这样,只要汽车表内有VIN输入数据库就会检验VIN输入结果。这就是保证数据库内数据完整性的另一种有效的措施。
以下是演示唯一性约束作为外键引用点的示例代码:
create table parent
(parent_id int not null, -- Primary key
parent_alternate_key int not null, -- Alternate key
parent_col1 int null,
parent_col2 int null,
constraint pk_parent_id primary key (parent_id),
constraint ak_parent_alternate_key unique_
(parent_id, parent_alternate_key)
)
go
insert parent values ( 1, 10, 150, 151)
insert parent values ( 2, 11, 122, 271)
insert parent values ( 3, 12, 192, 513)
insert parent values ( 4, 13, 112, 892)
go
create table child2
(child2_parent_id int not null, -- Primary key/Foreign key
child2_id int not null, -- Primary key
child2_col1 int null,
child2_parent_alternate_key int not null, -- Foreign key
constraint pk_child2 primary key (child2_parent_id, child2_id),
constraint fk_child2_parent foreign key (child2_parent_id)
references dbo.parent(parent_id),
constraint fk_pk_ak_child2_parent foreign key _
(child2_parent_id, child2_parent_alternate_key) _
references dbo.parent(parent_id, parent_alternate_key)
)
go
insert child2 values (1,1,34,10)
insert child2 values (4,2,34,13)
insert child2 values (2,3,34,11)
go
insert child2 values (1,4,34,23) -- This on
go
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?