-1

How to sorting data when contained in the underscore ?

Explanation is on the picture,,

enter image description here

Thank you for help.

Adit Prime
  • 13
  • 2
  • can the numbers be anny number? So `ABC_1_1` can also be `ABC_100_1000` ? And is the max of number of numbers always 2? – Raymond Nijland Jul 12 '19 at 09:30
  • 1
    Please, put your example in your question, don't use external image – Vincent Decaux Jul 12 '19 at 09:32
  • Hint: Research on this website how can split strings with nested SUBSTRING_INDEX functions and use CAST to convert it into a int.. Then you can simply use ORDER BY on those numbers .. Atleast if you are looking for a MySQL only method. – Raymond Nijland Jul 12 '19 at 09:34
  • 1
    Technically it **is** sorting correctly - you're sorting on strings so `10` comes before `2`. You'd be better off altering your database table to add a `priority` column that's an integer type and sorting on that. – CD001 Jul 12 '19 at 09:39
  • 1
    *"You'd be better off altering your database table to add a priority column that's an integer type and sorting on that. "* @CD001 most likely but we don't know the topicstarters usercase.. topicstarter keep in mind adding a "sorting" column only really works when you only need to deal with one "group" which you need to sort... – Raymond Nijland Jul 12 '19 at 09:47
  • @RaymondNijland digit numbers are unlimited, and can change – Adit Prime Jul 15 '19 at 03:51

3 Answers3

2

You want a natural sort.

<?php

$items =
[
'ABC_1_1',
'ABC_1_3',
'ABC_1_10',
'ABC_1_11',
'ABC_1_5',
'ABC_1_7'
];

sort($items, SORT_NATURAL);
var_dump($items);

Output:

array(6) {
    [0]=>
    string(7) "ABC_1_1"
    [1]=>
    string(7) "ABC_1_3"
    [2]=>
    string(7) "ABC_1_5"
    [3]=>
    string(7) "ABC_1_7"
    [4]=>
    string(8) "ABC_1_10"
    [5]=>
    string(8) "ABC_1_11"
  }
Progrock
  • 7,373
  • 1
  • 19
  • 25
1

You can try below -

select id_code
from tablename
order by 
substring_index(substring_index(id_code,'_',-2),'_',1),substring_index(id_code,'_',-1)
Fahmi
  • 37,315
  • 5
  • 22
  • 31
0

You can try in MYSQL to split your string, and order by parts :

SELECT SUBSTRING_INDEX(ID_DATA, '_', 1) as part1,
       SUBSTRING_INDEX(SUBSTRING_INDEX(ID_DATA, '_', 2), '_', -1) as part2,
       SUBSTRING_INDEX(ID_DATA, '_', -1) as part3,
FROM table
ORDER BY part1, part2, part3
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84