如何在SQL表中有2个主键时自动增加ID值?

huangapple go评论60阅读模式
英文:

How to autoincrement ID value when there are 2 primary keys in an SQL table?

问题

我正在制作一个包括帖子和评论的社交媒体应用,因此我创建了PostComment表。Comment是一个弱实体,因此它有两个主键:comment_idpost_id

在创建一条帖子的评论时,comment_id始终显示为None。我该如何为comment_id分配自动增加的值?

CREATE TABLE Post(
    post_id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    title VARCHAR(100),
    content TEXT,
    date DATETIME,
    FOREIGN KEY (user_id) REFERENCES NonAdmin(user_id)
);

CREATE TABLE Comment (
    comment_id INTEGER PRIMARY KEY AUTOINCREMENT,
    post_id INTEGER,
    user_id INTEGER NOT NULL,
    content TEXT,
    date DATETIME,
    FOREIGN KEY (user_id) REFERENCES NonAdmin(user_id),
    FOREIGN KEY (post_id) REFERENCES Post(post_id)
);
英文:

I am making a social media app that includes posts and comments, therefore I created Post and Comment tables. Comment is a weak entity, so that it has 2 primary keys: comment_id and post_id.

When creating a comment on a post, comment_id always appears as None. How can I assign auto incremented values to comment_id?

CREATE TABLE Post(
    post_id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    title VARCHAR(100),
    content TEXT,
    date DATETIME,
    FOREIGN KEY (user_id) REFERENCES NonAdmin(user_id)
);

CREATE TABLE Comment (
    comment_id INTEGER,
    post_id INTEGER,
    user_id INTEGER NOT NULL,
    content TEXT,
    date DATETIME,
    PRIMARY KEY (comment_id, post_id),
    FOREIGN KEY (user_id) REFERENCES NonAdmin(user_id),
    FOREIGN KEY (post_id) REFERENCES Post(post_id)
);

答案1

得分: 3

你应该将comment_id设为主键,如果你想要一个规范化的表格。如果你想将相同的评论分配给多篇文章,那么你应该创建第三个带有适当关系的表格。然而,我不明白为什么相同的评论要附加到不同的文章上。

CREATE TABLE Comment (
    comment_id INTEGER PRIMARY KEY AUTOINCREMENT,
    post_id INTEGER,
    user_id INTEGER NOT NULL,
    content TEXT,
    date DATETIME,
    FOREIGN KEY (user_id) REFERENCES NonAdmin(user_id),
    FOREIGN KEY (post_id) REFERENCES Post(post_id)
);
英文:

You should have only comment_id as your primary key if you want to have normalized table. If you want to assign the same comment to many posts, then you should create 3rd table with the proper relations. However, I don't see the reason why the same comment should be attached to the different posts.

CREATE TABLE Comment (
    comment_id INTEGER PRIMARY KEY AUTOINCREMENT,
    post_id INTEGER,
    user_id INTEGER NOT NULL,
    content TEXT,
    date DATETIME,
    FOREIGN KEY (user_id) REFERENCES NonAdmin(user_id),
    FOREIGN KEY (post_id) REFERENCES Post(post_id)
);

huangapple
  • 本文由 发表于 2023年5月29日 01:37:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定