I have a MySQL database set-up in a hierarchy style. There are 4 tables called pages, regions, elements, and content. Pages is at the top, and content is at the bottom.
To simplify:
pages has the column:
id
regions has the columns:
id
page_id
elements has the columns:
id
region_id
content has the columns:
id
element_id
I want to be able to delete all the children of pages using just the page’s id.
So far, I’ve been able to use a nested select statement to select the bottom content using the page’s id, but that doesn’t select the elements, regions, or the page.
SELECT * FROM `content` WHERE `element_id` IN (
SELECT `id` FROM `elements` WHERE `region_id` IN (
SELECT `id` FROM `regions` WHERE `page_id` IN (
SELECT `id` FROM `pages` WHERE `id` = 1
)
)
)
Anyway to do this efficiently? Thanks.
Thanks to @Hago and @Churk, here’s my final solution (basically Churk’s code, a tiny bit modified):
DELETE `content`, `elements`, `regions` FROM `content`
JOIN `elements` ON `elements`.`id` = `content`.`element_id`
JOIN `regions` ON `regions`.`id` = `elements`.`region_id`
JOIN `pages` ON `pages`.`id` = `regions`.`page_id`
WHERE `pages`.`id` = 1
1 Answer