database - MySQL Deleting related rows when they are not in another table -


i have table on 100 users never finished signin process. i'm trying delete users together data associated them.

since table relations not added previous developer working on this, have queries manually.

i came following right now

the last of 3 queries tries delete companies don't have company_id in users table, companies don't have user associated them.

the locations , tags constraint kick in, have delete first. that's how built query.. it's lot of code , it's hard read. way improve this?

delete locations company_id in (select id companies  not exists (select null users users.company_id =  companies.id));  delete tags company_id in (select id companies  not exists (select null users users.company_id =  companies.id));  delete companies not exists (select null users  users.company_id = companies.id); 

what i've tried

  • using set @todelete = (select...) : it's throwing errors subquery returns more 1 record.

am doing right way? or can simplified?

thank you!

there's not difference between approach , mine. please consider attempt make solution readable

since trying delete data location \ tags \ companies tables having lonely company_id, first need find out companies lonely. definition of lonely company - a company don't have adherence user said lonely in context.

the following query provides id of lonely companies:

select      c.company_id companies c  not exists(     select          1         users u          u.company_id = c.company_id     ); 

now can delete data location table associated lonely companies using above helper query.

delete  l locations l  inner join (     select          c.company_id     companies c      not exists(         select          1         users u          u.company_id = c.company_id     ) ) helper on l.company_id = helper.company_id; 

in approach can delete data other tables too.

see delete join in mysql


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -