mysql - Delete from table A where no children exist in table A and no children exist in table B -


i have traditional parent/child table simple tree categorisation , 'page' table pages linked categories:

    **table: cat**     c_id     c_name     parent_id      **table: page**     p_id     page_name     c_id 

i perform deletion only if there no child categories in cat table , no child pages in page table. know how counting , checking first. but, want know if can achieved elegantly in single query , affected rows.

i've tried , doesn't work i think disallowed select target table in delete query?

    delete      cat     c_id=x     , not exists (     select count( distinct p_id ) pages                            page     c_id =x     )     , not exists (     select count( distinct c_id ) children                            cat     parent_id =x     ); 

a delete join work, when deleting joined table. here left join check if there connections (c2 possible parent, , p possible referring page)

finally delete rows there no connections (ie connections return null);

delete c1 cat c1 left join cat c2    on c1.c_id = c2.parent_id left join page p   on c1.c_id = p.c_id c2.parent_id null  , p.c_id null  , c1.c_id = 1 

an sqlfiddle test with.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -