You want a foreign key on the questions
(resp: answers
) table that references the users
table and that deletes all questions (resp: answers) of a user when it is removed from the users
table.
This should work as per design:
alter table answers add constraint answers_users
foreign key(user_id)
references users(user_id)
on delete cascade
;
alter table questions add constraint questions_users
foreign key(user_id)
references users(user_id)
on delete cascade
;
Consider this demo:
-- create the tables
create table users (user_id int primary key);
create table questions(question_id int primary key, user_id int);
create table answers(answer_id int primary key, user_id int);
-- add the constraints
alter table answers add constraint answers_users
foreign key(user_id)
references users(user_id)
on delete cascade
;
alter table questions add constraint questions_users
foreign key(user_id)
references users(user_id)
on delete cascade
;
-- insert a few records - we have two users: 1 and 2
insert into users values (1), (2);
insert into questions values(1, 1), (2, 2);
insert into answers values(1, 1), (2, 2);
-- now delete user 1
delete from users where user_id = 1;
-- the corresponding record was removed from "questions"
select * from questions;
question_id | user_id
----------: | ------:
2 | 2
-- ... and it was removed from "answers" as well
select * from answers;
answer_id | user_id
--------: | ------:
2 | 2