简体   繁体   中英

How group_concat in order

My table structure is

cat_id  cat_desc    parent_category par_cat_order   cdate               status
1       Machine                                     2017-12-22 13:10:51 active
2       Woods                                       2017-12-22 13:11:01 active
3       Tools                                       2017-12-22 13:11:10 active
4       Perol           1           1               2017-12-22 13:11:30 active
5       Diesel          1           1               2017-12-22 13:11:43 active
6       Table           2           2               2017-12-22 13:11:59 active
7       Chair           2           2               2017-12-22 13:12:13 active
8       Round Table     6           2,6             2017-12-22 13:12:32 active
9       Dining          6           2,6             2017-12-22 13:13:01 active
10      Cuting Player   3           3               2017-12-22 13:13:15 active
11      Scrow Driver    3           3               2017-12-22 13:13:40 active
12      Sandal          9           2,6,9           2017-12-22 13:32:23 active

My want to display parent category desc insted of category number in both ('parent_category','par_cat_order')

My query is

select a.cat_id,
a.cat_desc,
 b.cat_desc,
 group_concat(c.cat_desc) 
 from category a 
 left JOIN category b on (a.parent_category=b.cat_id) 
 left JOIN category c on find_in_set(c.cat_id,a.par_cat_order) 
 GROUP by a.cat_id

and the output is

cat_id  cat_desc        cat_desc    group_concat(c.cat_desc)
1       Machine     
2       Woods       
3       Tools       
4       Perol           Machine     Machine
5       Diesel          Machine     Machine
6       Table           Woods       Woods
7       Chair           Woods       Woods
8       Round Table     Table       Table,Woods
9       Dining          Table       Table,Woods
10      Cuting Player   Tools       Tools
11      Scrow Driver    Tools       Tools
12      Sandal          Dining      Dining,Table,Woods

My need is the 'group_concat (c.cat_desc)' display the fields in stored order. For eg I stored in 'par_cat_order' as 2,6 for 8th record. It will display Woods, Table. But it display "Table, Woods"

You can use order by in group_concat

 select a.cat_id,
 a.cat_desc,
 b.cat_desc,
 group_concat(c.cat_desc order by c.cat_id asc) 
 from category a 
 left JOIN category b on (a.parent_category=b.cat_id) 
 left JOIN category c on find_in_set(c.cat_id,a.par_cat_order) 
 GROUP by a.cat_id

It would be better if you could normalize your table structure Database normalization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM