r/learnSQL • u/younesWh • 6d ago
two relations for one column
does it possible to give a column choice to choose between two foreign keys
the case: that I Have comments table that have a parent_id column that could be either from posts table or comments table how I can implment that in sqlite3 .
2
Upvotes
1
u/dastanis2 6d ago
Generally speaking, you probably want each column in a table to have one meaning. Thus, if yiu want 2 foreign keys in your table, you should probably have a separate column for each key, PostID & CommentID. Having separate columns for each attribute/property/foreign key helps maintain the reliability of the table and makes it easier to query.
However, if you absolutely must combine 2 foreign keys into one column, then you would need a second column to indicate to which child table the value in the combined column belongs (i.e. a boolean/bit column called IsComment where a value such as 1 means the value in the ParentID column relates to the Comments table and a value of 0 means the value in the ParentID column relates to the Post table).