2

I have a number of mysql tables with different table structures and all they have the followings table names and fieldnames (the ones of the left are table names and on the right are field names)

I want to be able to delete the values of the rows using a single variable (example $id = somename) in a single query

    user  id,
    user_image  user
    user_interest  user 
    user_lang  id 
    user_login  user
    user_personal  user
    user_prefer user
    user_reviewuser
    user_role user_id
    user_translang  user
    user_translate  user
    user_web  id

Also, a particular userid may not be present across all tables.

I am not sure at all on how to delete them all at once. Any tips would be appreciated, i looked at a couploe of similar questions but couldn't find a proper answer.

1
  • forign key index would make this a snap Commented Oct 2, 2014 at 20:56

2 Answers 2

3

You want to create a foreign key constraint, and specify "ON DELETE CASCADE". You'll need this for each of your tables that has a foreign key to user. For example,

ALTER TABLE user_image
ADD CONSTRAINT fk_user_image_user FOREIGN KEY (user)
    REFERENCES user(id)
    ON DELETE CASCADE;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Will it matter if any of those tables dont have the user in their tables ?
No. If there's nothing to delete, nothing will be deleted.
2

You can use the multi-table DELETE syntax. You need to use a LEFT JOIN in case any of the related tables do not have a corresponding row.

DELETE user, user_image, user_interest, ...
FROM user
LEFT JOIN user_image ON user.id = user_image.user
LEFT JOIN user_interest ON user.id = user_interest.user
...
WHERE user.id = $id

DEMO

However, if you relate the tables using a foreign key constraint, with ON DELETE CASCADE, you can just delete the row from the user table, and all the related rows will be deleted.

1 Comment

Thanks, ON DELETE CASCADE is a better option I GUESS.

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.