开发者

update table based on subquery of table

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开发者_如何学Go   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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜