Full answer
Option 1, polymorphic pair (no referential integrity):
text
comments(id, parent_type TEXT, parent_id BIGINT, body)Deleting a post leaves orphaned comments unless application code cleans up.
Option 2, exclusive foreign keys:
text
comments(id, post_id REFERENCES posts, photo_id REFERENCES photos, video_id REFERENCES videos, body,
CHECK ((post_id IS NOT NULL)::int + (photo_id IS NOT NULL)::int + (video_id IS NOT NULL)::int = 1))Real foreign keys and cascades work; adding a new parent type needs a new column.
Option 3, supertype table:
text
commentables(id PK, kind)
posts(id PK REFERENCES commentables(id), ...)
comments(id, commentable_id REFERENCES commentables(id), body)One foreign key, any number of parent kinds, at the cost of creating a commentables row with each parent.
Option 4, separate tables per parent (post_comments, photo_comments) is simple but duplicates logic.
The CHECK syntax shown casts booleans as in PostgreSQL; SQLite accepts the comparison results directly as 0 and 1. Not run here.
Key points
- Polymorphic pairs lack foreign keys
- Exclusive FKs with a CHECK enforce integrity
- A supertype table generalises
- Separate tables duplicate logic
- Choose by how often parent types are added
Common mistakes
- Relying on application code for integrity
- Allowing several parent columns set at once
Follow-ups
- How would you count comments per parent across types?
- How do ORMs map each option?
Tips
- Compare integrity across the options