首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >表中混合复杂主键

表中混合复杂主键
EN

Stack Overflow用户
提问于 2018-05-26 12:34:50
回答 1查看 53关注 0票数 -2

我从我的大学得到了一个数据库项目作为整个学期的家庭作业,在我的一个表中,有可能有一个如下格式的主键001SALS201812101自动递增实际上这个主键定义如下

001 - Branch Code
SALS - TRN Type
2018 - Current Year
122 - days of the year
101 - the auto increment number

有没有人能告诉我怎么做这样的主键

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-26 19:08:00

这不是我建议在表中做的事情。而是在依赖于表的视图中。

让数据库做它擅长的事情,即一个标准的自动递增integer作为主键。

如果您需要确保组合的唯一键,只需添加唯一的索引/ (SQL Server / MySQL)即可。

下面是一个使用SQL Server的示例:

create table Sales (
    Id int identity primary key
    ,BranchCode int
    ,TRNType varchar(25)
    ,Year int
    ,DaysOfYear int
);

create unique index ux_sales_key on Sales (BranchCode, TRNType, Year, DaysOfYear);
go

请注意,自2016年起,SQL Server支持computed columns。这也将解决您的问题,并且在表本身中。

现在在MySQL中使用相同的表结构

create table Sales (
    Id int auto_increment primary key
    ,BranchCode int
    ,TRNType varchar(25)
    ,Year int
    ,DaysOfYear int
    ,unique key (BranchCode, TRNType, Year, DaysOfYear)
);

要制定您的“组合键”,请使用类似以下内容的视图:

create view vSales
as
    select
        concat(BranchCode, TRNType, Year, DaysOfYear, Id) as SomeCompositeKey
        -- the rest of your cols go here
    from
        Sales;
go
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50539351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档