0

I have numbers like this: 666/2014, 01/2014, 1/2014, 02/2014, 125/2014, 06/2014 ...etc as STRING named 'n_inscription' in database. I want to retrieve those strings In ORDER from database

I used this:

$sql_students = $bd->query("SELECT * FROM `es_student_infos`
                            WHERE school_year='$school_year'
                            ORDER BY right(n_inscription, 4) * 1,
                            substring_index(n_inscription, '/', 1) * 1");

I get result like this: 01/2014, 02/2014, 06/2014, 1/2014, 125/2014, 666/2014

and the result I'm looking for is like this: 01/2014, 1/2014, 02/2014, 06/2014, 125/2014, 666/2014

any suggestion please?

Mariem
  • 39
  • 1
  • 1
  • 10

2 Answers2

2

The correct way is change the type of n_inscription to date/datetime/timestamp and then use order by as default.

There's more advantages to use date fields like comparison and date calculations, so I suggest you do like this.

EDIT: Change the order by collumn to school_year and not n_inscription:

 SELECT * FROM `es_student_infos`
                            WHERE school_year='$school_year'
                            ORDER school_year
Murilo Azevedo
  • 331
  • 1
  • 2
  • 7
  • The numbers I gave above are not dates.. those are students ids, the first number represent the student ID and the second represent the school year – Mariem Nov 29 '14 at 20:01
2

The best approach is probably to normalize the input so normal sorting does what you want it to do. For example, store the student number and year in two separate INTEGER columns and then ORDER BY studentNumber ASC, inscriptionYear ASC.

If that's absolutely not possible:

SELECT
  *
FROM
  es_student_infos
ORDER BY
  CAST(RIGHT(n_inscription, 4) AS UNSIGNED) ASC,
  CAST(LEFT(n_inscription, LOCATE('/', n_inscription) - 1) AS UNSIGNED) ASC

Link to fiddle demonstrating the solution: http://sqlfiddle.com/#!2/a5538/1/0

Tomas Creemers
  • 2,645
  • 14
  • 15
  • its still not working. the result i get with your query like this: 1/2014, 125/2014, 666/2014, 01/2014, 02/2014, 06/2014, and what i want is this order: 1/2014, 01/2014, 02/2014, 06/2014, 125/2014, 666/2014, OR 01/2014, 1/2014, 02/2014, 06/2014, 125/2014, 666/2014, because 01/2014 is the same as 1/2014 and 02/2014 is the same as 2/2014 as well, no difference between theme – Mariem Nov 29 '14 at 20:28
  • @Mariem: it seems to work for me. I've added sorting per year and an SQL fiddle to demonstrate the solution. Is it still not working for you? – Tomas Creemers Nov 29 '14 at 20:30