java - sorting by code -
i have food categories in db like:
category_id | parent_id | code | name -------------+-----------+--------+---------------------------------- 1 | | | root 2 | 1 | 1 | vegetables 11 | 1 | 10 | seeds 54 | 11 | 10.1 | sunflower seeds 12 | 1 | 11 | sugar , candy 22 | 2 | 1.1 | frozen vegetables
i want sort either code
in query or programmatically using parent_id (in pojo after mapping). effect should this:
1 ---1.1 ------1.1.1 ------1.1.2 ------1.1.3 ---1.2 2 3 ---3.1 ...
i tried order code
received records ordered like: 1, 10.1.1, 11, 1.1.1 should try sort in query or when it's mapped. maybe there interfaces/other utils in java purpose?
code
type character varying , i'm using postgresql
something this. sorts parent_id because sorting on varchar column code
column not easy due mismatch between character ordering , numeric ordering.
with recursive cat_tree ( select category_id, parent_id, name, array[category_id] sort, category_id::text path category parent_id null union select c.category_id, c.parent_id, c.name, p.sort||c.category_id, p.path||'.'||c.category_id category c join cat_tree p on p.category_id = c.parent_id ) select category_id, parent_id, path, name cat_tree order sort;
sqlfiddle: http://sqlfiddle.com/#!12/fab3c/1
Comments
Post a Comment