-2

I have two tables body_part and video_customised.

Table -> body_part

+-----+-----------|
| id  | title     |  
------------------|
| 1     Abs
| 2     Chest
| 3     Neck
------------------ 

Table -> video_customised

+-----+-----------|
| id  | body_part |  
------------------|
| 1     2,1,3     |
------------------|

SQL

SELECT  vc.body_part  ,
  GROUP_CONCAT(bp.name ORDER BY vc.body_part) 
 as body_part_name FROM 
 `video_customised` `vc`
LEFT JOIN `body_part` as `bp` ON 
  `FIND_IN_SET`(bp.id, vc.body_part); 

Result

+-----+-----------------------|
| body_part  | body_part_name |  
------------------------------|
| 2,1,3         Abs,Chest,Neck|     
------------------------------| 

Expected Result:

+-----+-----------------------|
| body_part  | body_part_name |  
------------------------------|
| 2,1,3         Chest,Abs,Neck|     
------------------------------|  

I want to GROUP_CONCAT body_part_name, its order should be same as body_part.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Shubham Azad
  • 786
  • 2
  • 10
  • 25

1 Answers1

4

You need to fix your data model. You should not be storing lists of numbers in a single field. Why?

  • In SQL tables, a column should contain a single value.
  • Numeric values should be stored as numbers not strings.
  • Foreign key relationships should be properly defined.
  • SQL has relatively poor string processing capabilities.
  • SQL is not designed to optimize queries on strings.

You should be using a junction/association table, with one row per body part and per video.

That said, sometimes we are stuck with other peoples really, really, really bad design decisions. In such a case, you can do what you want using find_in_set():

SELECT vc.body_part,
       GROUP_CONCAT(bp.name ORDER BY FIND_IN_SET(bp.id, vc.body_part)) as body_part_names
FROM video_customised vc LEFT JOIN
     body_part bp
     ON FIND_IN_SET(bp.id, vc.body_part); 
GROUP BY vc.body_part;
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786