sql - Mysql query using group_concat and self referencing id in the table -
here table , sample data.
create table `sections` ( `section_id` int(11) not null auto_increment, `name` varchar(100) not null, `parent_section_id` int(11) default null, primary key (`section_id`) ); insert `sections` (`section_id`, `name`, `parent_section_id`) values (1, 'city', null), (2, 'supplements', 4), (3, 'news', 5), (4, 'sunday', 2), (5, 'monday', 2), (6, 'tuesday', 2), (7, 'wednesday', 2), (8, 'thursday', 2), (9, 'friday', 2), (10, 'saturday', 2), (11, 'home', 4), (12, 'games', 4), (13, 'sites', 5), (14, 'sports', 5), (15, 'cyber space', 6);
parent_section_id foreign key referencing section_id in same table can have null if doesn't belong other section.
how can below output have tried using group_concat function doesn't give exact result. parent_section_id pointing id same table. should use other column achieve below output or use other table keep track of sections contains sub sections. please me solve problem or suggest other approach
id, name, subsections ---------------------- 1, 'city', null 2, 'supplements', 'sunday,monday,tuesday,wednesday,thursday,friday,saturday' 3, 'news', null 4, 'sunday', 'homes,games' 5, 'monday','sites,sports' 6, 'tuesday', 'cyber space' 7, 'wednesday', null 8, 'thursday', null 9, 'friday', null 10, 'saturday', null 11, 'home', null 12, 'games', null 13, 'site', null 14, 'sports', null 15, 'cyber space',null
here sql fiddle link http://sqlfiddle.com/#!9/e9767/2
final query
select s1.section_id, s1.name, group_concat(s2.name) subsections, (select name sections section_id = s1.parent_section_id) 'parentname' sections s1 left join sections s2 on s1.section_id = s2.parent_section_id group s1.section_id;
you can result want using (left) self-join on section_id = parent_section_id
so:
select s1.section_id, s1.name, group_concat(s2.name) subsections sections s1 left join sections s2 on s1.section_id = s2.parent_section_id group s1.section_id;
Comments
Post a Comment