1

We have product codes that go as follows:

  • AGE100 (stands for AGE 1.00 ounce)
  • AGE050 (stands for AGE 0.50 ounce)
  • AGE025 (stands for AGE 0.25 ounce)
  • AGE010 (stands for AGE 0.10 ounce)

So on and so forth. I would like the database to return them alphabet first, then by the number code at the end, so KR100 would be lower than AGE050.

My current query,

 SELECT * FROM  'prices' ORDER BY  'code' ASC LIMIT 0 , 30

Returns:

  1. AGE010
  2. AGE025
  3. AGE050
  4. AGE100
  5. KR100

How would I make it sort the numbers in the code properly?

Charles Zink
  • 3,482
  • 5
  • 22
  • 24

3 Answers3

0

To sort descending by the number portion:

SELECT * FROM  'prices' ORDER BY SUBSTRING('code', -3) DESC

and the first 2 chars

SELECT * FROM  'prices' ORDER BY SUBSTRING('code', 1,2) ASC

so this should give you a something close:

SELECT * FROM  'prices' ORDER BY SUBSTRING('code', 1,2) ASC, SUBSTRING('code', -3) DESC
Chris
  • 2,955
  • 1
  • 30
  • 43
0

To place items in a specific order you could use an sortby column in the database that you can change to finely adjust the order that the rows should be pull out in.

Example

SELECT * FROM  'prices' ORDER BY  'code' ASC LIMIT 0 , 30

would become

SELECT * FROM  'prices' ORDER BY  'sortby' ASC LIMIT 0 , 30

This field would be an INT and would make it much easier to get the desired order.

mic
  • 1,251
  • 2
  • 15
  • 33
-1

Since natsort() doesn't work with multidimensional arrays, you can try:

uksort($array, 'strnatcasecmp');

eidsonator
  • 1,319
  • 2
  • 11
  • 25