views:

1232

answers:

1

I am using the nested set model to store a large hierarchy of data in a local SQLite database on an iPhone. I read the MySQL tech article from their web site on how to do this, but one of the queries they suggest (and that I need) doesn't appear to work with SQLite and I'm not sure how to get around it.

SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM line_items AS node,
    line_items AS parent,
    line_items AS sub_parent,
    (SELECT node.name, (COUNT(parent.name) - 1) AS depth
        FROM line_items AS node,
        line_items AS parent
        WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND node.name = 'Power Up'
        GROUP BY node.name
        ORDER BY node.lft
    ) AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
    AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
    AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth <= 1
ORDER BY node.lft;

SQLite reports that sub_tree.name isn't a column, and I assume this is because its subquery implementation is incomplete. Does anyone have any ideas about how to get around this limitation?

The purpose of the query is to get all the immediate children of a given parent node.

+1  A: 

Try using "node.name AS name" in the subquery, i.e.

SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM line_items AS node,
    line_items AS parent,
    line_items AS sub_parent,
    (SELECT node.name AS name, (COUNT(parent.name) - 1) AS depth
        FROM line_items AS node,
        line_items AS parent
        WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND node.name = 'Power Up'
        GROUP BY node.name
        ORDER BY node.lft
    ) AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
    AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
    AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth <= 1
ORDER BY node.lft;

At least seems to get rid of the error.

cmeerw
Almost totally fixed it. For some reason the HAVING DEPTH <= 1 part wasn't having any effect. Turned out that it was getting confused between the sub_tree.depth and top-level depth. I just changed the name of the top level one and it worked. Thanks!
Marc W