0

I have mysql table with has field product_name which has data something like

SKL-05
TIP-01
TIP-02 L/R
TIP-12 UV
TIP-120 L/R
TIP-121 L/R
TIP-13 L/R

I want to sort that result like as follow

SKL-05
TIP-01
TIP-02 L/R
TIP-12 UV
TIP-13 L/R
TIP-120 L/R
TIP-121 L/R

Means numberwise in the string 01, 02, 03 etc Please help me guys...

Thanks in Advance !!

2
  • Use substring() function to strip off the first characters. Commented Jul 20, 2011 at 11:56
  • ORDER BY CAST(SUBSTRING_INDEX(SUBSTRING(product_name,5),' ',1) AS INT) might work. Commented Jul 20, 2011 at 12:00

3 Answers 3

2
SELECT product_name FROM table1 
ORDER BY substring(product_name FROM 5) 

http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_substring

This will kill any index you have on product_name though, if you need speed, add an extra field numeric_product_name with an index on that.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try using the SUBSTRING() and SUBSTRING_INDEX() functions of MySQL: String functions

Try:

ORDER BY CAST(SUBSTRING_INDEX(SUBSTRING(product_name,5),' ',1) AS INT)

or

ORDER BY CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(product_name,' ',1),'-',-1) AS INT)

Comments

0

There are a couple of options:

  1. Reformat the codes to allow them to be ordered naturally, eg.

     TIP-121 L/R     -->  TIP-121 L/R
     TIP-13 L/R      -->  TIP-013 L/R
    
  2. Split the string up into its parts and order on them individually. This can get a bit horrible if there are lots of parts. eg.

    SELECT code
    FROM table
    ORDER BY 
        SUBSTR(code, 1, 4), 
        CAST(SUBSTR(code, 5, LOCATE(' ', code)) AS UNSIGNED)
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.