How to make a identity column for a 2-key primary key

时间:2018-08-20 20:40:40

标签: sql sql-server

Here is my fictional tables:

Post{
    Post-Id int primary key identity,
    Post-another-columns blahblahblah
}

Lamp{
    Lamp-Id int primary key identity,
    Lamp-another-columns blahblahblah
}

Post-Lamp(n-n Relationship){
    Post-Id FOREIGN KEY REFERENCES Posts(Post-Id), 
    Lamp-Id FOREIGN KEY REFERENCES Lamp(Lamp-Id), 
    Lamp-Index int not null, --(describe the Lamp index that is in this Post)
    Post-Bar-another-columns blahblahblah,
    CONSTRAINT PK_Post_Lamp PRIMARY KEY NONCLUSTERED ([Post-Id], [Lamp-Id])
}

On my .Net code, every time that i put a Lamp into a Post, i insert a index based at the MAX index that a Post has of the Lamps. It's a foreach Lamp in Post, insert into Post-Lamp(postId, index, lampId), but this seems very wrong. How can i make a incremental column for the Lamp-Index that respects each change of Post-Id?

Edit: .Net code

int postId = await _repositories.Post.Add(post);

List<LampPost> lamps = model.Lamp.Select((l, i) => new { Lamp = l, Index = i })
                .Select(item => new LampPost
                {
                    LampId= item.Lamp,
                    LampIndex = item.Index,
                    PostId = postId,
                }).ToList();

            await _repositories.Lamp.Add(lamps);

3 个答案:

答案 0 :(得分:1)

您的问题标题听起来像您想要一个composite primary key,但我认为您通过示例所要实现的只是一张带有2个外键的表,如下所示:

create table Posts(
  PostId int, 
  OtherColumn varchar(50), 
  primary key (PostId)
)

create table Lamps(
  LampId int, 
  OtherColumn varchar(50), 
  primary key (LampId)
)

create table PostLamp(
  PostId int FOREIGN KEY REFERENCES Posts(PostId), 
  LampId int FOREIGN KEY REFERENCES Lamps(LampId), 
)

答案 1 :(得分:1)

嗯,也许您可​​以使用视图轻松解决此问题。

首先使用和标识列创建链接表,例如:

CREATE TABLE postlamp_t
             (post integer,
              lamp integer,
              lampindex integer IDENTITY,
              PRIMARY KEY (post
                           lamp),
              FOREIGN KEY (post)
                          REFERENCES post
                                     (id),
              FOREIGN KEY (lamp)
                          REFERENCES lamp
                                     (id));

现在使用row_number()窗口函数创建一个视图以计算每个帖子的索引。

CREATE VIEW postlamp
AS
SELECT post,
       lamp,
       row_number() OVER (PARTITION BY post
                          ORDER BY lampindex) lampindex
       FROM postlamp_t;

只要您不尝试更新计算所得的列,此视图就可以更新,并且可以像使用实际的链接表一样使用它(INSERTUPDATE,{{1 }},DELETE

db<>fiddle找到演示。

(附带说明:如果一次不应该将一个灯放在两个不同的位置上,如果我们在谈论实际的现实灯,这似乎很现实,请在链接表中考虑对灯的唯一约束。)

答案 2 :(得分:0)

两者之间有什么区别
Lamp-Id外键参考Lamp(Lamp-Id)和Lamp-Index int不为null ??

我对标题有点困惑,但是似乎您应该查看SCOPE_IDENTITY()。它返回插入到同一作用域的标识列中的最后一个标识值。在插入灯的存储过程中,在Lamp表中插入值。在插入灯后,使用Scope_Identity()设置一个变量,然后在Lamp-Post插入查询中使用该变量。