0

I have a users table and it is possible for one or more users to become related. I have a column in the database called referred and if it has an ID in it, if that ID gets deleted from the database, then the associated users must go too.

Here is my query:

START TRANSACTION;
DELETE FROM users
WHERE id IN 
  ( SELECT a.id
    FROM users a 
      JOIN users b ON a.referred = b.id );

If I remove user Josh Murray with id='1', anyone that matches criteria referred='1' must be deleted also.

3
  • DELETE FROM users WHERE id = 1 AND referred = 1 ? Commented Oct 26, 2017 at 10:35
  • is your referred column was announced as foreign key? if yes, then simply adding on delete cascade option will do the job Commented Oct 26, 2017 at 10:36
  • See: Why should I provide an MCVE for what seems to me to be a very simple SQL query? Commented Oct 26, 2017 at 10:41

2 Answers 2

1

I would suggest to create table with foreign keys with specifying action ON DELETE for example:

ALTER TABLE users
    ADD CONSTRAINT FK_REFERRED
    FOREIGN KEY (referred)
    REFERENCES users(id)
    ON DELETE CASCADE

So that if for example user with ID = 4 was referencing to user with ID = 1 and another user with ID = 7 is referencing to the first user(ID = 4), when user with ID = 1 is deleted, user with ID = 4 will be also deleted, and user with ID = 7 will be deleted too.

So you wouldn't bother with deleting all other 'children' nodes of the data

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer - works as expected and exactly what I was looking for!
1

will this not do ?

Delete from users where (id = 1 or referred = 1)

1 Comment

what about those that were referred to 1, but also were referred by others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.