I'm trying to implement the Nested Subset algorithm to handle hierarchies in a relational database (MySQL).
Specifically I'm following this excellent guide at http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
The algorithm for insertion gives the following query to insert a new node and renumber all nodes:
SELECT @myRight := rgt FROM nested_category
WHERE name = 'TELEVISIONS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myRight;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myRight;
INSERT INTO nested_category(name, lft, rgt) VALUES('GAME CONSOLES', @myRight + 1, @myRight + 2);
I have tried to insert the above in a JPA Native Query as follows:
Query query = em.createNativeQuery("SELECT @myRight := rgt FROM nested_category
WHERE name = 'TELEVISIONS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myRight;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myRight;
INSERT INTO nested_category(name, lft, rgt) VALUES('GAME CONSOLES', @myRight + 1, @myRight + 2);");
query.getResultList();
But I get an Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
Is there some way to modify the above query into an equivalent query or somehow let Native Query handle the above query?
I tried some nested subquery as follows:
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > (SELECT rgt FROM nested_category WHERE name = 'TELEVISIONS');
But I get an #1093 - You can't specify target table 'nested_category' for update in FROM clause
apparently I can't update from a table from which I select.