r/learnSQL • • Jul 23 '26

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 .

3 Upvotes

7 comments sorted by

View all comments

Show parent comment

1

u/younesWh Jul 25 '26

I will go with trigger one

CREATE TRIGGER IF NOT EXISTS comment_satisfy

BEFORE INSERT ON comments

BEGIN

SELECT CASE	

	WHEN NOT EXISTS(SELECT \* FROM comments WHERE id = NEW.parent_id)

	AND NOT EXISTS(SELECT \* FROM posts WHERE id = NEW.parent_id) 

	THEN RAISE(ABORT, "parent not exists")

END;

END;