Reputation: 11
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. 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?
Upvotes: 1
Views: 426
Reputation: 175586
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
)
Upvotes: 1