SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Question ordering strings containing numbers

    Hello,

    Consider, if you will, the following product codes:
    BK1
    BK1a
    BK2
    BK3
    BK11
    BK22

    That would be that 'natural' order of things as far as a human is concerned.

    MySQL would order them thusly:
    BK1
    BK11
    BK1a
    BK2
    BK22
    BK3

    I can understand that logic, but how can I convince MySQL to come round to my way of thinking?

    Many thanks,
    M

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,216
    Mentioned
    58 Post(s)
    Tagged
    3 Thread(s)
    try
    Code:
    ORDER BY 0+SUBSTRING(productcode FROM 2)
    it's a hack, but it works
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hey r937,

    Thanks for your reply. Unfortunately, just to make things easier, product codes do not necessarily have 2 letters at the start:

    DVD1a
    BK2PB
    DVD1S
    UMW16

    are all examples of product ids...

    I'm wondering if I should change the table:
    Code:
    CREATE TABLE `catalogue` (
    `prefix` VARCHAR(3) NOT NULL,
    `suffix` VARCHAR(5) NOT NULL,
    ...
    PRIMARY KEY(`prefix`, `suffix`)
    Then the query would something like:
    Code:
    SELECT `prefix`+`suffix` AS `id` FROM `catalogue` ORDER BY `prefix` AND `suffix`
    What do you think?

  4. #4
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    ... well more like
    Code:
    SELECT CONCAT(`prefix`, `suffix`) AS `id` FROM `catalogue` ORDER BY `prefix`, 0+`suffix`
    which works a treat!

  5. #5
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,216
    Mentioned
    58 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by mickyginger View Post
    which works a treat!
    my job here is done

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •