update table based on subquery of table

十年热恋 提交于 2019-12-13 03:55:31

问题


I have am using a closure table for some page heirarchy. I want to be able to delete a page and update the level of the children it leaves.

par child level
1   1     0
1   2     1
2   2     0
1   3     2
2   3     1
3   3     0
1   4     3
2   4     2
3   4     1
4   4     0

Prior to deleting page 3 I've attempted to update the levels and then deleteing reocrds for page 3 the goal of such being:

par child level
1   1     0
1   2     1
2   2     0
1   4     2
2   4     1
4   4     0

describing this with a (invalid) suquery like so:

UPDATE tbl_page_structures
SET page_level = page_level - 1 
WHERE
    child IN ( SELECT child FROM tbl_page_structures WHERE par = 3 )
AND page_level != 0;
DELETE ... where par=3 or child=3;

which obviously fails on the update.

Ideally would like to complete in one query but if tmp able is way to go then so be it - performace on this is more important that sweet sql sweetness...


回答1:


Try:

UPDATE tbl_page_structures
SET page_level = page_level - 1 
WHERE
    child IN (SELECT * FROM( SELECT child FROM tbl_page_structures WHERE par = 3 ))
AND page_level != 0;
DELETE ... where par=3 or child=3;

As @Mark said:

Currently, you cannot update a table and select from the same table in a subquery.

Source: http://dev.mysql.com/doc/refman/5.5/en/update.html

But you can if you do the inner select in a sub-sub-query.



来源:https://stackoverflow.com/questions/7471388/update-table-based-on-subquery-of-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!