javascript - mysql query for children and grandchildren -


column view

+-----------------------+ | name                  | +-----------------------+ | electronics           | |  televisions          | |   tube                | |   lcd                 | |   plasma              | |  game consoles        | |  portable electronics | |   mp3 players         | |    flash              | |   cd players          | |   2 way radios        | |    frs                | +-----------------------+ 

table core.category

id      parentid   name  1       null       electronics 2       1          televisions 3       2          tube 4       2          lcd 5       2          plasma 6       1          game consoles 7       1          portable electronics 8       7          mp3 players 9       8          flash 10      7          cd players 11      1          2 way radios 12      11         frs 

if select 1,

result (shows children , grandchildren) expect there more 1 grandparent(electronics)

+-----+ | id  | +-----+ | 1   | | 2   | | 3   | | 4   | | 5   | | 6   | | 7   | | 8   | | 9   | | 10  | | 11  | | 12  | +-----+ 

if select 2

result must be

+-----+ | id  | +-----+ | 2   | | 3   | | 4   | | 5   | +-----+ 

i got selected category , children ( need more output grandchildren)

module.exports.categorysearch = function(searchcategory, cb) {   var query = 'select category_id \    core.category c \    category_id = $1::integer union    select category_id \    core.category c \    category_parentid = $1::integer ;';   var map = function(err, result) {      if(err) {         return cb(err, null);       }       var list = [];       result.rows.foreach(function(row, i) {         list.push(new category(row));       });       cb(null, list);     };   repository.querydb(query, [searchcategory], map); }; 

result is

+-----+ | id  | +-----+ | 1   | | 2   | | 6   | | 7   | | 11  | +-----+ 

what should add select statement

with recursive categorytree (   select c.category_id, 0 depth   core.category c   c.category_id = $1::integer    union    select c.category_id, t.depth + 1 depth   core.category c   inner join categorytree t     on t.category_id = c.category_parentid )  select category_id categorytree 

shows selected , children , grandchildren , on...

+-----+ | id  | +-----+ | 1   | | 2   | | 3   | | 4   | | 5   | | 6   | | 7   | | 8   | | 9   | | 10  | | 11  | | 12  | +-----+ 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -