SwVitaliy

Untitled

Jul 12th, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. mysql> describe a;
  2. +-----------+-------------+------+-----+---------+----------------+
  3. | Field     | Type        | Null | Key | Default | Extra          |
  4. +-----------+-------------+------+-----+---------+----------------+
  5. | id        | int(11)     | NO   | PRI | NULL    | auto_increment |
  6. | parent_id | int(11)     | YES  | MUL | NULL    |                |
  7. | name      | varchar(45) | NO   |     | NULL    |                |
  8. +-----------+-------------+------+-----+---------+----------------+
  9. 3 rows in set (0.04 sec)
  10.  
  11. mysql> select * from a;
  12. +----+-----------+------+
  13. | id | parent_id | name |
  14. +----+-----------+------+
  15. |  1 |      NULL | ROOT |
  16. |  2 |         1 | L1_0 |
  17. |  3 |         1 | L1_1 |
  18. |  4 |         2 | L2_0 |
  19. |  5 |         4 | L3_0 |
  20. |  6 |         4 | L3_1 |
  21. |  7 |         3 | L2_1 |
  22. +----+-----------+------+
  23. 7 rows in set (0.00 sec)
  24.  
  25. mysql> set @t=5; select distinct b.node_id, a.* from a, (select @t:=if(a.id = @t, a.parent_id, @t) as node_id from a order by a.id DESC) as b where a.id=b.node_id; # ищем путь от ноды с индексом 5 до корня, при условии, что дочерний элемент имеет индекс выше, чем свои родитель
  26. Query OK, 0 rows affected (0.00 sec)
  27.  
  28. +---------+----+-----------+------+
  29. | node_id | id | parent_id | name |
  30. +---------+----+-----------+------+
  31. |       5 |  5 |         4 | L3_0 |
  32. |       4 |  4 |         2 | L2_0 |
  33. |       2 |  2 |         1 | L1_0 |
  34. |       1 |  1 |      NULL | ROOT |
  35. +---------+----+-----------+------+
  36. 4 rows in set (0.02 sec)
Advertisement
Add Comment
Please, Sign In to add comment