简体   繁体   English

外键可以引用同一表中的主键吗?

[英]Can a foreign key reference the primary key in the same table?

I'm creating a comment system under a post article. 我正在文章下创建评论系统。 I have one table for comments with ID, post_id, user_id, text and comment_id column. 我有一张表,用于ID,post_id,user_id,text和comment_id列的注释。 So my thinking is, that when I add a comment under some post, the comment_id will be set to null, but if I comment another comment, the comment_id will be set to ID of the comment ID I'm commenting, which leads me to my question: is it possible to have foreign key that references the ID in the same table or is there a better way to solve this? 所以我的想法是,当我在某个帖子下添加评论时,comment_id将设置为null,但是如果我评论其他评论,则comment_id将设置为我正在评论的评论ID的ID,我的问题:是否可以在同一张表中使用引用ID的外键,或者有解决此问题的更好方法?

Can a foreign key reference the primary key in the same table? 外键可以引用同一表中的主键吗?

Yes, it is possible: 对的,这是可能的:

CREATE TABLE comments(
  id INT PRIMARY KEY,
  comment_id INT REFERENCES comments(id)
  -- other columns
)

db<>fiddle demo db <> fiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM